1. 题目
给定一个二叉树,确定它是否是一个完全二叉树。
百度百科中对完全二叉树的定义如下:
若设二叉树的深度为 h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。(注:
第 h 层可能包含 1~ 2h 个节点。)
示例 1:
输入:[1,2,3,4,5,6]
输出:true
解释:最后一层前的每一层都是满的(即,结点值为 {1} 和 {2,3} 的两层),且最后一层中的所有结点({4,5,6})都尽可能地向左。
示例 2:
输入:[1,2,3,4,5,null,7]
输出:false
解释:值为 7 的结点没有尽可能靠向左侧。
提示:
树中将会有 1 到 100 个结点。
Related Topics 树
👍 132 👎 0
2. 题解
2.1 解法1: 层序遍历
若为完全二叉树, 则层序遍历过程中, 在空节点之后不会再出现非空节点
class Solution {
public boolean isCompleteTree(TreeNode root) {
if (root == null) {
return true;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
TreeNode pre = root;
while (!queue.isEmpty()) {
TreeNode curr = queue.poll();
if (pre == null && curr != null) {
return false;
}
pre = curr;
if (curr != null) {
queue.offer(curr.left);
queue.offer(curr.right);
}
}
return true;
}
}
2.2 解法2: 先序遍历+完全二叉树的性质
- 完全二叉树有性质: 用 1 表示根节点,对于任意一个节点 v,它的左孩子为 2v 右孩子为 2v + 1
- 在先序遍历过程中计算二叉树所有结点的个数, 同时根据点 1中完全二叉树的性质, 统计最大的结点编号
- 最后的结果判断树的结点个数 是否 等于 最后一个节点的编号 indexCode!
class Solution {
int size = 0;
int maxIndex = 0;
public boolean isCompleteTree(TreeNode root) {
dfs(root, 1);
return size == maxIndex;
}
public void dfs(TreeNode root, int indexCode) {
if (root == null) {
return;
}
size++;
maxIndex = Math.max(maxIndex, indexCode);
dfs(root.left, 2 * indexCode);
dfs(root.right, 2 * indexCode + 1);
}
}
参考:
很简单的思路,代码很简洁
官方题解评论