跳至主要內容

958. 二叉树的完全性检验


958. 二叉树的完全性检验

🟠   🔖  广度优先搜索 二叉树  🔗 力扣open in new window LeetCodeopen in new window

题目

Given the root of a binary tree, determine if it is a complete binary tree.

In a complete binary treeopen in new window , 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: 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:

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;
};