ITeye博客

Balanced Binary Tree

testforvln · 2012-11-01 23:38 · OJ_leetcode · 编程语言 · Markdown


/**
 * 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) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if (root == null)
            return true;
        else {
            if (!isBalanced(root.left) || !isBalanced(root.right))
                return false;
            else if (Math.abs(getDepth(root.left) - getDepth(root.right)) <= 1)
                    return true;
                else
                    return false;
        }
    }
    
    public int getDepth(TreeNode root){
        if (root == null)
            return 0;
        else 
            return Math.max(getDepth(root.left), getDepth(root.right)) + 1;
    }
}

小测试过了 大测试超时= = 哎。。。递归果然就是时间效率不高 想了一下发现是isBalanced中已经用isBalanced算过一次深度了 之后又算一次深度 囧


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.HashMap;
public class Solution {
    static HashMap<TreeNode, Integer> depths = new HashMap<TreeNode, Integer>();
    public boolean isBalanced(TreeNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if (root == null)
            return true;
        else {
            if (!isBalanced(root.left) || !isBalanced(root.right))
                return false;
            else if (Math.abs(getDepth(root.left) - getDepth(root.right)) <= 1)
                    return true;
                else
                    return false;
        }
    }
    
    public int getDepth(TreeNode root){
        if (root == null)
            return 0;
        else 
            if (depths.containsKey(root))
                return depths.get(root);
            else{
                depths.put(root, Math.max(getDepth(root.left), getDepth(root.right)) + 1);
                return depths.get(root);
            }
    }
}

啊 然后写了一个HashMap存了一下深度就好了。。。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。