anonymous
2009-04-29 05:25:30 UTC
Here are the first 10 lines, for example:
1 75 2 4
2 68 6 7
3 58 9 10
4 88 12 15
5 28 18 19
6 27 21 22
7 24 24 25
8 5 28 29
9 69 31 34
10 61 37 38
For example, the first line of the file is 1 75 2 4. It means that value of the node with key 1 is 75, key (line of file) of the left child of this node is 2, and key of right child is 4. Note: not all nodes in the file are part of the tree. Some lines in the file are there just to confuse you. What is the depth of this tree? (Depth is defined as the total number of nodes along the longest path.)
Now, I have some code I think will work. It compiles. It won't run though. Here is the code and below is what comes up in the command window:
import java.util.*;
import java.io.*;
class Depth
{
static Scanner sc;
static List
public static void main(String[]args) throws Exception
{
String filename = "src/data.txt";
try
{
sc = new Scanner(new File("tree.input"));
}
catch (FileNotFoundException e)
{
}
while(sc.hasNextLine())
{
int[] row = new int[4];
row[0] = sc.nextInt();
row[1] = sc.nextInt();
row[2] = sc.nextInt();
row[3] = sc.nextInt();
dump.add(row);
}
TreeNode top = new TreeNode(dump.get(0)[1]);
build(top, dump.get(0)[2], dump.get(0)[3]);
System.out.println("The depth of the tree is " + top.depth() + ".");
}
static TreeNode build(TreeNode n, int left_child_key, int right_child_key)
{
TreeNode leftNode = new TreeNode(left_child_key);
TreeNode rightNode = new TreeNode(right_child_key);
if(left_child_key != -1)
{
build(leftNode, getLeftChildKey(left_child_key), getRightChildKey(left_child_key));
n.setLeft(leftNode);
}
if(right_child_key != -1)
{
build(rightNode, getLeftChildKey(right_child_key), getRightChildKey(right_child_key));
n.setRight(rightNode);
}
return n;
}
static int getLeftChildKey(int key)
{
for(int[] row: dump)
{
if(row[0] == key)
return row[2];
}
return -1;
}
static int getRightChildKey(int key)
{
for(int[] row: dump)
{
if(row[0] == key)
return row[3];
}
return -1;
}
}
class TreeNode
{
int value;
TreeNode leftChild, rightChild;
TreeNode(int v)
{
value = v;
}
public void setLeft(TreeNode l)
{
leftChild = l;
}
public void setRight(TreeNode r)
{
rightChild = r;
}
public int depth()
{
int ld = 0, rd = 0;
if (leftChild != null) ld = leftChild.depth();
if (rightChild != null) rd = rightChild.depth();
return Math.max(ld, rd) + 1;
}
}
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at HW.main(HW.java:26)
Let me know what you guys think is wrong. Thanks!