ASU Interview Question
AccountantsCountry: United States
Each node of the tree should have same height of it's left and right subtree. That solves it. If not true the method returns -1.
public int preOrder(Node root){
if(root==null){
return 0;
}
int lHeight = preOrder(root.getLChild());
if(lHeight == -1){
return -1;
}
int rHeight = preOrder(root.getRChild());
if(rHeight == -1){
return -1;
}
if(lHeight!=rHeight){
return -1;
}
return lHeight + 1;
}
Number of nodes in the binary tree is 2^n-1. So just count the number of nodes in the binary tree, and return true if the count is equal to 2^n-1. where n is the height
that is great exept I have no idea what is n (n equals to..?). all I have is the tree root.
n is number of nodes in the tree
int height(Tree n)
{
if n == null return 0;
return max(height(n.left), height(n.right)) + 1;
}
int count(Tree n)
{
if n == null return 0;
return count(n.left) + count(n.right)) + 1;
}
bool isFullTree(Tree t)
{
int h = height(t);
int count = count(t);
return 2^h -1 == count
}
use BFS. That is. As we put node into queue, we count the number of items. Once we remove items from queue and inserts it's child, we are reaching the next level. first level we have 1 node, second level, 2, and then 4 and so on. There should be 2^i items at each level where i is the ith level.
- hiuhchan April 29, 2015