题目:判断一棵树是否为平衡二叉树
思路:根据上一题的二叉树的深度,在递归过程中加上标识符,递归到当前节点,判断当前子树是不是一个平衡二叉树,如果不是,就把标识符置为false,返回标识符即可。
代码:
private boolean result = true;
public boolean IsBalanced_Solution(TreeNode root) {
TreeDepth(root);
return result;
}
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
if (Math.abs(left - right) > 1) {
result = false;
}
return (left > right) ? (left + 1) : (right + 1);
}