PEAK6 Interview Question

Find the height of a binary tree

Interview Answers

Anonymous

Jun 27, 2011

The above post gives too big of an answer except in trees that are technically Linked Lists. Replace the return line with the following to *actually* get the height of a tree: return 1 + max(heightOfTree(node.left), heightOfTree(node.right)); Also, the above function could possibly terminate without returning anything. Add an else condition that returns 0 as the base case.

5

Anonymous

Mar 3, 2012

/** Returns the max root-to-leaf depth of the tree. Uses a recursive helper that recurs down to find the max depth. */ public int maxDepth() { return(maxDepth(root)); } private int maxDepth(Node node) { if (node==null) { return(0); } else { int lDepth = maxDepth(node.left); int rDepth = maxDepth(node.right); // use the larger + 1 return(Math.max(lDepth, rDepth) + 1); } }

2

Anonymous

May 15, 2011

Class Node { int data; Node left; Node right; } public static int heightOfTree(Node node) { if(node!=null) { return (heightOfTree(node.left)+1+heightOfTree(node.right)); } }

1