How to determine whether a binary tree is a Complete Binary Tree

Source: Internet
Author: User

Yan Weimin's statement in this textbook: a binary tree with a depth of K and a number of nodes of 2 ^ k-1 is a full binary tree. This concept is well understood,

It is a tree with a depth of K and no space available.

First, number the full binary tree in the order of breadth first traversal (from left to right.

A k-tree with N nodes in depth also numbers the tree. If all the numbers correspond to full-tree trees, the tree is a Complete Binary Tree.

 

Any binary tree can be supplemented into a full binary tree. In this way, there will be a lot of holes in the middle. During the breadth-first traversal, if it is a full binary tree or a full Binary Tree, these holes are at the end of the breadth-first traversal, the entire binary tree has been traversed. If it is not a complete binary tree,

When we traverse the holes, we will find that there are no traversal values behind the holes. In this way, you only need to determine whether the entire tree is completely a binary tree based on whether to traverse to the empty tree or not.

The algorithm is as follows:

Bool is_complete (TREE * root) <br/>{< br/> queue Q; <br/> tree * PTR; <br/> // perform breadth-first traversal (hierarchical traversal) and put null nodes in the queue <br/> q. push (Root); <br/> while (PTR = Q. pop ())! = NULL) <br/>{< br/> q. push (PTR-> left); <br/> q. push (PTR-> right); <br/>}</P> <p> // determine whether there are still unaccessed nodes <br/> while (! Q. is_empty () <br/>{< br/> PTR = Q. pop (); </P> <p> // if there are unaccessed non-null nodes, the tree is empty and the non-completely Binary Tree <br/> If (null! = PTR) <br/>{< br/> return false; <br/>}</P> <p> return true; <br/>}

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.