Microsoft Interview Question
Country: India
Interview Type: Written Test
we can do it using BFS idea.
for every node popped we have to just check it it has both left and right children. If for any node this is not true i.e either it has no children or 1 child then we see for all the left over nodes in the queue if they have any children or not. if anyone of them has a child then its not complete binary tree else it is.
The following code depends on definition that says in a complete binary tree all the nodes should have exactly 2 nodes (or) none.
boolean isCompleteBT(Node* root) {
If (*root != null) {
return ((*root->left == null && *root->right == null) || (*root->left != null && *root->right != null)) && isCompleteBT(*root->left) && isCompleteBT(*root->right);
}
return true;
}
Complete binary tree is a tree which contains elements, such that if put in an array representation of ll there wont be any empty cell between the first and last data.
Just did some pointer correction, otherwise this is correct.
boolean isCompleteBT(Node* root) {
If (root != null) {
return ((root->left == null && root->right == null) || (root->left != null && root->right != null)) && isCompleteBT(root->left) && isCompleteBT(root->right));
}
return true;
}
using the definition a tree of height h will have 2^h-1 nodes in it...count the number of nodes using any traversal using stack coz better then recursion and then find height of the tree then chk..
Using the following "definition" of complete tree:
The idea is to do a breadth first search while maintaining a number n with each node. And when we enque its children, we give the left child number 2n and right child 2n+1.
If the BFS does not return numbers in order 1,2,3 ..., M. Then it is not a complete tree. Otherwise it is.
Pseudo Code:
- Anonymous September 03, 2012