/* * TreeDepth.java * */ import net.datastructures.*; public class TreeDepth { // Get the depth of node v public static int depth (Tree t, Position v) { if (t.isRoot(v)) return 0; else return 1 + depth(t, t.parent(v)); } public static void main(String[] args) { LinkedBinaryTree t = new LinkedBinaryTree(); Position parent, E; int d; /* generate a tree t, insert 9 nodes */ t.addRoot(new MyData1('A')); parent = t.root(); t.insertLeft(parent, new MyData1('B')); t.insertRight(parent, new MyData1('C')); parent = t.left(t.root()); t.insertLeft(parent, new MyData1('D')); t.insertRight(parent, new MyData1('E')); parent = t.right(t.root()); t.insertLeft(parent, new MyData1('F')); t.insertRight(parent, new MyData1('G')); parent = t.right(t.left(t.root())); t.insertLeft(parent, new MyData1('H')); t.insertRight(parent, new MyData1('I')); /* print the structure of tree t */ MyData1.printTree(t); /* get the depth of E */ E = t.right(t.left(t.root())); d = depth (t, E); System.out.println("The depth of E is " + d); } }