How to infer that 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 very understandable,

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

First, the full binary tree is numbered 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.

 

A random binary tree can be combined into a full binary tree. In this way, there will be many holes in the middle. In the case of breadth-first traversal, assume that it is a full binary tree or a full binary tree. These holes are at the end of the breadth-first traversal. Therefore, when we traverse to holes, the entire binary tree has been traversed. Assume that it is a non-Complete Binary Tree,

When we traverse the holes, we will find that there are no traversal values behind the holes. In this way, we only need to infer whether a Complete Binary Tree is based on whether to traverse to a hole or whether the whole tree traversal is over.

The algorithm is as follows:

Bool is_complete (TREE * root) {queue Q; tree * PTR; // performs breadth-first traversal (hierarchical traversal) and puts null nodes into the queue Q. push (Root); While (PTR = Q. pop ())! = NULL) {q. Push (PTR-> left); q. Push (PTR-> right);} // infer whether there are still nodes not asked by the operator while (! Q. is_empty () {PTR = Q. Pop (); // if a non-empty node is not found, the tree has holes. If (null! = PTR) {return false ;}} return true ;}

How to infer that 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.