A complete binary tree is defined as a binary tree in which every level, except possibly the deepest, is completely filled. At deepest level, all nodes must be as far left a
bool isComplete (struct Node* root){
if(root==NULL)
return true; // Recur for left and right subtree
bool flag=false;
int option1=height(root->left);
int option2=height(root->right);
if(option1==option2||option1==option2+1)
flag=true;
return flag&&isComplete(root->left)&&isComplete(root->right);
}
please consider as a correct answer if you found useful.
The simplest procedure is:
If condition satisfy tree, is complete binary tree, else not.
That's a simple algorithm and turning it into a working code shouldn't be a problem if you are good enough coder.
You could combine three pieces of information from the subtrees:
Whether the subtree is complete
The maximal height
The minimal height (equal to maximal height or to maximal height - 1)
private static boolean isCompleteBinaryTree(TreeNode root) {
if (root == null) {
return false;
} else {
boolean completeFlag = false;
List<TreeNode> list = new ArrayList<TreeNode>();
list.add(root);
while (!list.isEmpty()) {
TreeNode element = list.remove(0);
if (element.left != null) {
if (completeFlag) {
return false;
}
list.add(element.left);
} else {
completeFlag = true;
}
if (element.right != null) {
if (completeFlag) {
return false;
}
list.add(element.right);
} else {
completeFlag = true;
}
}
return true;
}
}
Reference: Check the following link for a detailed explanation http://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/