[LeetCode] 958. 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:
Input: [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
Example 2:
Input: [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
Note:
- The tree will have between 1 and 100 nodes.
这道题给了一棵二叉树,让我们判断是否是一棵完全二叉树 Complete Binary Tree,通过题目中的解释可知,完全二叉树除了最后一行之外,所有位置都是满员的,而且最后一行的结点都是尽可能靠左的,注意跟完满二叉树 Full Bianry Tree 区分开来。最简单直接的方法就是按层序遍历二叉树,当遇到空结点时,后面若还出现非空结点,则一定不是完全二叉树。具体到写法就是先把根结点放入到队列中,然后进行循环,条件是队首结点不为空。在循环中取出队首结点,然后将其左右子结点加入队列中,这里不必判断子结点是否为空,为空照样加入队列,因为一旦取出空结点,循环就会停止。然后再用个循环将队首所有的空结点都移除,这样若是完全二叉树的话,队列中所有还剩的结点都应该是空结点,且都会被移除,若队列中存在非空结点,说明不是完全二叉树,最后只要判断队列是否为空即可,参见代码如下:
解法一:
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q{{root}};
while (q.front() != NULL) {
TreeNode *cur = q.front(); q.pop();
q.push(cur->left);
q.push(cur->right);
}
while (!q.empty() && q.front() == NULL) {
q.pop();
}
return q.empty();
}
};
下面这种解法思想都一样,只不过写法略有不同,这里使用了一个变量 found,初始化为 false,然后还是用层序遍历,当取出的结点为空结点时,比较 found 为 true,然后继续遍历。当遍历到非空结点时,若此时 found 为 true 了,则直接返回 false 即可。当循环退出后,返回 true, 参见代码如下:
解法二:
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q{{root}};
bool found = false;
while (!q.empty()) {
TreeNode *cur = q.front(); q.pop();
if (!cur) {
found = true;
} else {
if (found) return false;
q.push(cur->left);
q.push(cur->right);
}
}
return true;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/958
参考资料:
https://leetcode.com/problems/check-completeness-of-a-binary-tree/