Leetcode110 Balanced Binary Tree

方法1没什么好说的,就是基本思想,通过对比每个结点两个子树的高度,递归的判断:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        boolean isB = Math.abs(getHeight(root.left)-getHeight(root.right))>1?false:true;
        return isB&&isBalanced(root.left)&&isBalanced(root.right);
    }
    public static int getHeight(TreeNode T) {
        if(T==null) return 0;
        else if(T.left==null&&T.right==null) {return 1;}
        else if(T.left!=null&&T.right==null) {return getHeight(T.left)+1;}
        else if(T.left==null&&T.right!=null) {return getHeight(T.right)+1;}
        else {return Math.max(getHeight(T.left), getHeight(T.right))+1;}
    }
}

然后是方法2,会破坏树的结点,理论上可以省去每次都调用getHeight函数的时间,但是在树的高度都比较低的时候提高就不太明显:

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        if(getHeight(root)==1) return true;
        if(root.left!=null&&root.right==null) return root.left.val<=1;
        if(root.left==null&&root.right!=null) return root.right.val<=1;
        return Math.abs(root.left.val-root.right.val)<=1&&isBalanced(root.left)&&isBalanced(root.right);
    }
    public static int getHeight(TreeNode T) {
        if(T==null) return 0;
        else if(T.left==null&&T.right==null) {T.val=1;return 1;}
        else if(T.left!=null&&T.right==null) {T.val=getHeight(T.left)+1;return T.val;}
        else if(T.left==null&&T.right!=null) {T.val=getHeight(T.right)+1;return T.val;}
        else {T.val=Math.max(getHeight(T.left), getHeight(T.right))+1;return T.val;}
    }
}

时间和方法1一毛一样。

posted @ 2019-03-21 21:20  大胖子球花  阅读(76)  评论(0)    收藏  举报