Description
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] |
Note:
- The tree will have between 1 and 100 nodes.
解法
按层遍历二叉树节点,无论当前节点的子节点是否为空均加入队列,如果在队列中碰到为空的节点,那么如果是一棵完全树,则队列中的剩余元素必都为空,否则是不完全的。
具体代码如下:
1 | /** |