Determine if the binary tree is a complete binary tree. The definition of a complete binary tree is that the former n-1 layer is full, the nth layer if there is a vacancy, is missing on the right side, that is, the nth layer of the rightmost node, its left is full, the right is empty.
The description of this problem has been prompted to understand the method, using breadth-first traversal, starting from the root node, into the queue, if the queue is not empty, looping. Encounter the first node that has no left son or right son, set the flag bit, if you later encounter a left/right son node, then this is not a complete binary tree.
This method needs to traverse the entire tree, the complexity is O (n), and N is the total number of nodes.
#include <iostream> #include <queue>using namespace Std;bool leftmost =false;queue<node*> Q;bool Processchild (node* node) {if (node) {if (!leftmost) {q.push_back (node);} Elsereturn false;} Elseleftmost=true;return true;} BOOL Iscompletebinarytree (node* root)//sequence Traversal {if (root==null) return true;q.push_back (root); while (!q.empty ()) {node* Node=q.pop (); if (! Processchild (Node->left)) return false; Handle the right node if (! Processchild (Node->right)) return false; }return true;}
This article is from the "Small Stop" blog, please be sure to keep this source http://10541556.blog.51cto.com/10531556/1835456
Determine if a binary tree is a complete binary tree