Determine if a binary tree is a complete binary tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.