1 题目链接
https://www.nowcoder.com/exam/oj/ta?page=1&tpId=13&type=13
2 题目
3 思路 & 图解 & 代码
题目中指出判断一棵二叉树的条件有三个:
-
根节点的左子树是平衡二叉树
-
根节点的右子树是平衡二叉树
-
左右子树的高度的差的绝对值不超过1
【错误代码】
这个错误代码求解的是左右子树高度的差的绝对值不超过1,忽略了左右子树还都必须是平衡二叉树的要求
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
return Math.abs(deep(root.left)-deep(root.right)) <= 1;
}
【正确代码】
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
if (root.left == null && root.right == null) {
return true;
}
return IsBalanced_Solution(root.left)
&& IsBalanced_Solution(root.right)
&& Math.abs(deep(root.left) - deep(root.right)) <= 1;
}
public int deep(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
return Math.max(deep(root.left), deep(root.right)) + 1;
}
}