Check Completeness of a Binary Tree
Given a binary tree, determine if it is a complete binary tree.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example 1:
1 | Input: [1,2,3,4,5,6] |
Example 2:
1 | Input: [1,2,3,4,5,null,7] |
解法一:层次遍历
思路:层次遍历每一个节点,当遇到第一个叶子节点或最后一个非叶子节点时,判断此后的每一个节点都是叶子节点。
对于每一个节点,如果它是非叶子节点,那么它要么有两个孩子节点,否则,只有左孩子节点,如果一个节点有右孩子而没有左孩子,则该节点不是完全二叉树上的节点。
当一个节点只有左孩子,没有右孩子,则该节点是最后一个非叶子节点;如果一个节点既没有左孩子节点也没有右孩子节点,则该节点是第一个叶子节点。
1 | class Solution { |
解法二:
通过比较一棵完全二叉树中应有的节点总数和当前二叉树中的节点总数来判断是否是完全二叉树。这种思路是可行的,但是代码无法通过所有测试用例,原因是当二叉树的深度过深时,start的值会超出int允许的范围。
1 | /** |
相关题目
958. Check Completeness of a Binary Tree
222. Count Complete Tree Nodes
919. Complete Binary Tree Inserter