anonymous
2009-04-28 14:22:03 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.)
So... this is what I have so far:
import java.util.*;
import java.io.*;
class HW4
{
public static void main(String[]args) throws Exception
{
Scanner sc = new Scanner(new File("assignment_4.input"));
while(sc.hasNextLine())
{
int key = sc.nextInt();
int v = sc.nextInt();
int l = sc.nextInt(); //left child
int r = sc.nextInt(); // right child
TreeNode n = new TreeNode((TreeNode) key, (TreeNode) v, (TreeNode) l, (TreeNode) r); }
// System.out.println("The depth of the tree is " + depth + ".");
}
}
class TreeNode
{
int value;
TreeNode leftChild, rightChild;
TreeNode(TreeNode l, int v, TreeNode r)
{
value = v;
leftChild = l;
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;
}
}
What is wrong with my program? Obviously it doesn't work, but what do I do to fix it? If you want, you can do the whole problem and post it here. I have to find the depth of this tree with Java. Thank you! :)