Amazon Interview Question
Software Engineer / DevelopersNice use of a level-order traversal. From Wikipedia, here is helpful pseudocode for level-order traversal:
levelorder(root)
q ← empty queue
q.enqueue(root)
while (not q.isEmpty())
node ← q.dequeue()
visit(node)
if (node.left ≠ null)
q.enqueue(node.left)
if (node.right ≠ null)
q.enqueue(node.right)
Height Recursively
private static Integer heightRecursively(BinaryTreeNode root) {
int leftHeight, rightHeight;
if (root == null)
return 0;
else {
leftHeight = heightRecursively(root.getLeft());
rightHeight = heightRecursively(root.getRight());
if (leftHeight > rightHeight)
return leftHeight + 1;
else
return rightHeight + 1;
}
}
besides recursion way, traverse the binary tree by breath-first.
use a queque as an auxiliary and an empty tag.
queue.push(root)
queue.push(tag)
height = 0;
while(!queue.empty())
{
Node node = queue.pop();
if (node.isTag())
{
++height;
queue.push(node);
}
else
{
if (node.left != null)
queque.push(node.left);
if (node.right != null)
queue.push(node.right)
}
}
Binary_Tree_height(struct tree * node)
{
if(node==NULL)
return 0;
else
return(Binanry_Tree_height(node->left)+Binary_Tree_height(node->right)+1);
}
/*
Recursive algorithm to find height (or depth) of binary tree
O(n) time and space complexity.
Note: Assumes rooted tree with single node is height of 1.
*/
public static int binaryTreeHeight(BinaryTree.Node<Integer> root)
{
int leftHeight, rightHeight = 0;
if (root == null)
{
return 0;
} else {
leftHeight = binaryTreeHeight(root.left);
rightHeight = binaryTreeHeight(root.right);
//max of the heights of two children + 1
//instead of using Math.max
//or could do 1 + max(Height(T->left), Height(T->right))
if (leftHeight > rightHeight)
{
return (leftHeight + 1);
} else {
return (rightHeight + 1);
}
}
}
/*
uses level-order traversal (breadth-first traversal). end of level tag is null pointer.
Note: Assumes root height starts at 1.
O(n) time and space complexity
*/
public static int binaryTreeHeightIterative(BinaryTree.Node<Integer> root)
{
int level = 0;
Queue<BinaryTree.Node<Integer>> queue = new LinkedList<BinaryTree.Node<Integer>>();
if (root == null)
{
return 0;
}
queue.add(root);
//END of first level
queue.add(null);
while (!queue.isEmpty())
{
root = queue.poll();
//completion of CURRENT level
if (root == null)
{
//put another marker for next level
if (!queue.isEmpty())
{
queue.add(null);
}
//increase level
level++;
} else {
if (root.left != null)
{
queue.add(root.left);
}
if (root.right != null)
{
queue.add(root.right);
}
}
}
return level;
}
- Vir Pratap Uttam May 04, 2015