Thursday, December 12, 2013

Balanced Binary Tree LeetCode

简单题,如果时间复杂度为n方,这样每个节点都要算左右高度,然后判断是否差别大于1.
这样有些浪费时间,但是代码非常容易写出。如下:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null) return true; 
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        if(Math.abs(leftHeight - rightHeight) > 1) return false;
        return isBalanced(root.left)&&isBalanced(root.right);
    }
    
    public int getHeight(TreeNode root){
        if(root == null) return 0;
        return Math.max(getHeight(root.left), getHeight(root.right))+1;
    }
}

如果想要O(n),必须在算高度的时候做些手脚,就判断是否差别大于1. 差别大于1就返回-1,差别小于等于1就返回高度,继续判断向上判断下一个Node。
public class Solution {
    public boolean isBalanced(TreeNode root) {
       return height(root) != -1;
    }
    
    public int height(TreeNode root){
        if(root == null) return 0;
        int left = height(root.left);
        if(left == -1) return -1;
        int right = height(root.right);
        if(right == -1) return -1;
        
        if(Math.abs(left - right) > 1) return -1;
        return Math.max(height(root.left), height(root.right))+1;
    }
}

No comments:

Post a Comment