Check Completeness of a Binary Tree

update Dec 25, 16:19

LeetCodearrow-up-right

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:

Example 2:

Note:

The tree will have between 1 and 100 nodes.

Basic Idea:

我们注意到,如果一个树是完全二叉树,那么在BFS的过程中,一旦我们遇到null,后面就不可以有不是null的node,我们可以利用这一性质。简单来说就是写一个BFS,用一个boolean标记是否已经见过null,如果见过,当我们再遇到非null时直接返回false;

  • Java Code:

还有一种dfs的解法,没有这么直观,需要仔细分情况判断不符合条件的情况。

  • Java Code: