题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解题思路
平衡二叉树的左右子树的高度差最多是1;
private class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
private int getTreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = getTreeDepth(root.left);
if (left == -1) {
return -1;
}
int right = getTreeDepth(root.right);
if (right == -1) {
return -1;
}
return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(getTreeDepth(root.left), getTreeDepth(root.right));
}
public boolean IsBalanced_Solution(TreeNode root) {
return getTreeDepth(root) != -1;
}