完全二叉树和完全二叉树的区别
一种 二叉树是一种数据结构,每个节点最多只能有两个后代,分别命名为“左”和“右”孩子。
二叉树有不同的类型,但在这里我们将讨论完全二叉树和完全二叉树的区别。
完整的二叉树:
完全二叉树是所有节点都有 0 或 2 个后代的二叉树。换句话说,完全二叉树是一种二叉树,其中除叶节点外的所有节点都有两个后代。
Let, i be the number of internal nodes
n be the total number of nodes
l be number of leaves
λ be number of levels
Then,
The number of leaves is (i + 1).
The total number of nodes is (2i + 1).
The number of internal nodes is (n – 1) / 2.
The number of leaves is (n + 1) / 2.
The total number of nodes is (2l – 1).
The number of internal nodes is (l – 1).
The number of leaves is at most (2λ – 1).
完整的二叉树:
当二叉树的所有层都被完全填满时,除了最后一层,它可以包含 1 或 2 个子节点并从左开始填充,就称它是完全二叉树。
There are 2 points that you can recognize from here,
- The leftmost side of the leaf node must always be filled first.
- It isn’t necessary for the last leaf node to have a right sibling.
检查以下示例以更好地理解完整和完整的二叉树。
Example 1:
- Node C has just one child therefore, it is not a Complete binary tree.
- Node C also has a right child but no left child, therefore it is also not a Complete binary tree.
Hence, the binary tree shown above is neither complete nor full binary tree.
Example 2:
- All of the nodes have either 0 or 2 offspring, therefore, it is a Full binary tree.
- It is not a Complete binary tree because node B has no children whereas node C has children, and according to a complete binary tree, nodes should be filled from the left side.
Hence, the binary tree shown above is a Full binary tree and it is not a Complete binary tree.
Example 3:
- It is a complete binary tree as all the nodes are left filled.
- Node B has just one child, therefore, it is not a full binary tree.
Hence, the binary tree shown above is a Complete binary tree and it is not a Full binary tree.
Example 4:
- It is a Complete binary tree because all the nodes are left filled.
- All of the nodes have either 0 or 2 offspring, therefore, it is a full binary tree.
Hence, the binary tree shown above is both a complete and a full binary tree.
S. No. | Complete Binary Tree | Full Binary Tree |
1. | In a complete binary tree, a node in the last level can have only one child. | In a full binary tree, a node cannot have just one child. |
2. | In a complete binary tree, the node should be filled from the left to right. | There is no order of filling nodes in a full binary tree. |
3. | Complete binary trees are mainly used in heap-based data structures. | Full binary tree has no application as such but is also called a proper binary tree. |