Full Binary Tree: the structure of a binary tree with N nodes is the same as that of the first n nodes of the full binary tree.
How to determine whether a tree is a Complete Binary Tree
Sequence traversal is supported in only two steps.
Step 1: if only the right subtree does not have the left subtree after traversing a node, it is not a complete binary tree.
Part 2: If only the left subtree is traversed to a node, the node to be traversed later must be a leaf node. Otherwise, it is not a complete binary tree.
If the preceding conditions are excluded, the tree is a Complete Binary Tree.
Core code:
// Sequence traversal int layerorder (bitreenode * head) {bool flag = 0; lqueue Q; initiate_queue (& Q); bitreenode * P; If (Head! = NULL) appendqueue (& Q, head); While (queuenotempty (& Q) {If (FLAG) {If (p-> lchild! = NULL | p-> rchild! = NULL) return 0;} p = queuedelete (& Q); If (p-> lchild! = NULL) appendqueue (& Q, P-> lchild); If (p-> rchild! = NULL) appendqueue (& Q, P-> rchild); If (P-> lchild = NULL) & (p-> rchild! = NULL) return 0; // If the left subtree is empty and the right subtree exists, the right subtree is not completely empty. // If the left subtree exists, the right subtree is empty, set flag to 1 to further judge whether the node to be traversed is a leaf node if (p-> lchild! = NULL & P-> rchild = NULL) Flag = 1; // If the left subtree and the right subtree are empty, set flag to 1 for further judgment, determine whether the node to be traversed is a leaf node if (p-> lchild = NULL & P-> rchild = NULL) Flag = 1 ;}return 1 ;}
The complete code is as follows:
# Include <iostream> using namespace STD; typedef struct bitreenode {char data; struct bitreenode * lchild; struct bitreenode * rchild;} bitreenode; void initiate_tree (bitreenode ** head) {(* head) = (bitreenode *) malloc (sizeof (bitreenode); (* head)-> lchild = NULL; (* head)-> rchild = NULL ;} bitreenode * insertlchild (bitreenode * head, char X) {If (Head = NULL) return NULL; else {bitreenode * P1, * P2; P1 = head-> lchild; p2 = (bitreenode *) Malloc (sizeof (bitreenode); P2-> DATA = x; P2-> rchild = NULL; head-> lchild = P2; P2-> lchild = p1; return P2 ;}} bitreenode * insertrchild (bitreenode * head, char X) {If (Head = NULL) return NULL; {bitreenode * P1, * P2; p1 = head-> rchild; P2 = (bitreenode *) malloc (sizeof (bitreenode); P2-> DATA = x; P2-> lchild = NULL; head-> rchild = P2; P2-> rchild = p1; return P2 ;}} void DLR (bitreenode * head) {If (Head = NULL) return; else {cout
Determine by programming that a tree is a Complete Binary Tree (implemented using hierarchical traversal)