958. Check Completeness of a Binary Tree
958. Check Completeness of a Binary Tree
题目
Given the root
of a binary tree, determine if it is a complete binary tree.
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:
![](https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png)
Input: root = [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:
![](https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png)
Input: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
Constraints:
- The number of nodes in the tree is in the range
[1, 100]
. 1 <= Node.val <= 1000
题目大意
给定一个二叉树,确定它是否是一个完全二叉树。
完全二叉树的定义如下:
若设二叉树的深度为 h
,除第 h
层外,其它各层 (1 ~ h-1
) 的结点数都达到最大个数,第 h
层所有的节点都连续集中在最左边,这就是完全二叉树。(注:第 h
层可能包含 1~ 2h
个节点。)
解题思路
判断一棵二叉树是否为完全二叉树的常用方法包括层序遍历和递归两种。
思路一:层序遍历
层序遍历是从上到下、从左到右依次遍历二叉树的每一层节点。在层序遍历的过程中,对于每一个非空节点,都将其左右子节点(包括空节点)加入遍历队列。在遍历过程中,如果遇到一个节点为 null(空节点),则后续所有节点都应该是 null,否则不是完全二叉树。
思路二:递归
递归方法会使用节点编号的性质。对于任意节点 i
,其左子节点编号为 2 * i + 1
,右子节点编号为 2 * i + 2
。通过比较节点的编号和树中实际节点的数量,可以判断是否为完全二叉树。
代码
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isCompleteTree = function (root) {
if (!root) return true;
let queue = [root];
let foundNull = false;
while (queue.length) {
let node = queue.shift();
if (!node) {
foundNull = true;
} else {
if (foundNull) return false;
queue.push(node.left);
queue.push(node.right);
}
}
return true;
};
var isCompleteTree = function (root) {
const count = (root) => {
if (!root) return 0;
return 1 + count(root.left) + count(root.right);
};
// 计算整棵树的节点数量
const total = count(root);
const isComplete = (root, index) => {
// 如果当前节点为空,认为是完全二叉树的一部分
if (!root) return true;
// 如果当前节点的编号超过了总节点数量,说明不是完全二叉树
if (index >= total) return false;
// 递归检查左右子树
return (
isComplete(root.left, index * 2 + 1) &&
isComplete(root.right, index * 2 + 2)
);
};
// 从根节点开始递归检查
return isComplete(root, 0);
};