Binary tree concept
Binary trees are used a lot in practice.
A binary tree is a finite set of nodes , which is:
- or empty ;
- It consists of a root node plus two binary trees called left subtree and right subtree .
- A binary tree has at most two children .
Note here: a binary tree is not a tree of degree 2 .
The maximum degree of a binary tree is 2, which does not mean that its degree must be 2. So these four situations are also binary trees:
- empty tree
- only root node
- Only left subtree
- only right subtree
- Both left and right subtrees exist
There is no node with degree greater than 2 in a binary tree ;
The subtrees of a binary tree can be divided into left and right subtrees , and the order cannot be reversed , so the binary tree is an ordered tree .
Binary trees can also be commonly understood as "family planning" for trees. "Family planning" means having two children, but does it mean that every family has two children?
So does a tree with degree 2 have to be a binary tree?
- A degree of 2 must be a binary tree. If the degree is 2, then the maximum degree of all nodes is 2 , and the concept of a binary tree is that there is no node with a degree greater than 2.
- A binary tree is a special tree with a maximum degree of 2, but it does not say it must be 2.
special binary tree
full binary tree
A binary tree is a full binary tree if the number of nodes in each layer reaches the maximum . In other words, if the maturity of a binary tree is K, then the total number of nodes is , then it is a full binary tree.
According to the picture above:
- Assuming the height is h, then there will be nodes;
- So assuming that the tree has N nodes, that is ; then the height is .
complete binary tree
For a complete binary tree, the first h-1 levels are all full , and the last level may not be full, but it must be continuous from left to right .
A complete binary tree is a very efficient data structure, and a complete binary tree is derived from a full binary tree. For a binary tree with depth K and n nodes, it is called a complete binary tree if and only if each node corresponds to the nodes numbered from 1 to n in the full binary tree with depth K. It should be noted that a full binary tree is a special kind of complete binary tree.
Note here that the order of binary trees is fixed and must be continuous.
Assuming that the height of a complete binary tree is h, what is the number of nodes it has?
The range of the last level of a complete binary tree:
Idea:
- Here we want the number of nodes in a full binary tree to be ;
- Then the upper level in the full binary tree is ;
- Because a complete binary tree is a full binary tree, the last level is not full, that is, the number of nodes in the last level is at most and at least 1;
- Therefore, according to the proportional formula, the range of the last level of the complete binary tree can be calculated as: .