958. 二叉树的完全性检验
给定一个二叉树,确定它是否是一个完全二叉树。
百度百科中对完全二叉树的定义如下:
若设二叉树的深度为 h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。(注:第 h 层可能包含 1~ 2h 个节点。)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-completeness-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private Info solve(TreeNode root) {
if (root == null) {
return new Info(true, true, 0);
}
Info left = solve(root.left);
Info right = solve(root.right);
if (left.height == right.height) {
return new Info(left.ok && right.ok && left.isFull, left.isFull && right.isFull, left.height + 1);
} else if (left.height == right.height + 1) {
return new Info(left.ok && right.ok && right.isFull, false, left.height + 1);
} else {
return new Info(false, false, Math.max(left.height, right.height) + 1);
}
}
public boolean isCompleteTree(TreeNode root) {
if (root == null) {
return true;
}
return solve(root).ok;
}
}
class Info {
boolean ok;
boolean isFull;
int height;
public Info(boolean ok, boolean isFull, int height) {
this.ok = ok;
this.isFull = isFull;
this.height = height;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号