---
title: "Balanced Binary Tree"
author: "testforvln"
date: "2012-11-01T23:38:29Z"
tags: []
categories: ["编程语言"]
slug: "balanced-binary-tree"
draft: false
lastmod: "2012-11-01T23:38:29Z"
id: 1714148
url: "https://testforvln.iteye.com/blog/1714148"
---

```java

/**
 * 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算过一次深度了 之后又算一次深度 囧


```java

/**
 * 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存了一下深度就好了。。。