码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Balanced Binary Tree

时间:2015-04-11 13:13:13      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

题目地址:https://leetcode.com/problems/balanced-binary-tree/

题目解答:

/**
 * 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) {
        return isBalanced(root,new int[1]);
    }
    
    private boolean isBalanced(TreeNode root,int[] depth){
        if(root == null){
            depth[0] = 0;
            return true;
        }
        
        int temp = depth[0];
        boolean left = isBalanced(root.left,depth);
        int leftDepth = depth[0];
        
        depth[0] = temp;
        boolean right = isBalanced(root.right,depth);
        int rightDepth = depth[0];
        
        depth[0] = 1 + (leftDepth > rightDepth?leftDepth:rightDepth);
        
        int diff = rightDepth - leftDepth;
        
        if(diff >1 || diff < -1){
            return false;
        }
        
        return left&&right;
    }
}

 

Leetcode Balanced Binary Tree

标签:

原文地址:http://www.cnblogs.com/xiongyuesen/p/4417487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!