41.平衡二叉树

题目描述:

  输入一颗二叉树的根节点,判断该树是不是一颗二叉平衡树

思路分析:

  解法1:求出根节点左右子树的高度,如果左右子树的高度差不大于1,那么继续判断它的左右子树是不是二叉平衡树,如果左右子树都是二叉平衡树,那么最终这棵树就是二叉平衡树。

  解法2:解法1中思路比较清晰简单,但是一个节点会被重复遍历多次,这种思路的时间效率不高。我们用后序遍历的方式,遍历二叉树的每个节点,那么在遍历到一个节点之前我们就已经遍历了它的左右子树,只要在遍历每个节点的时候记录它的深度,我们就可以一边遍历一边判断每个节点是不平衡的。

代码:

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null)
            return true;
        int left=depth(root.left);
        int right=depth(root.right);
        if(Math.abs(left-right)>1)
            return false;
        return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
    }
    public int depth(TreeNode root){
        if(root==null)
            return 0;
        int left=depth(root.left);
        int right=depth(root.right);
        return Math.max(left,right)+1;
    }
}
public class Solution {
    boolean res=true;
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null)
            return res;
        depth(root);
        return res;
    }
    public int depth(TreeNode root){
        if(root==null)
            return 0;
        int left=depth(root.left);
        int right=depth(root.right);
        if(Math.abs(left-right)>1)
            res=false;
        return Math.max(left,right)+1;
    }
}

原文地址:https://www.cnblogs.com/yjxyy/p/10932559.html