剑指 Offer 55 - II. 平衡二叉树
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
后序遍历即最后遍历根节点,剪枝即从低部开始若底部子树不是平衡二叉树则返回-1,即最后遍历根节点。
public boolean isBalanced(TreeNode root) {
return maxDepth(root) != -1;
}
int maxDepth(TreeNode root){
if(root == null) return 0;
//左子树深度
int left = maxDepth(root.left);
if(left == -1) return -1;
int right = maxDepth(root.right);
//右子树深度
if(right == -1) return -1;
return Math.abs(right-left)< 2 ? Math.max(right,left) + 1 : -1;
}
先序遍历即先遍历根节点,判断深度(从顶至低)即先判断根节点的子树是否为平衡二叉树,继而判断下层子树。
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
//判断当前子树是否是平衡树(通过其左右子树深度相减是否小于等于1判断) 判断当前子树的左子树和右子树是否都是平衡树
return Math.abs(depth(root.left) - depth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
private int depth(TreeNode root) {
if (root == null) return 0;
return Math.max(depth(root.left), depth(root.right)) + 1;
}
}