首页 > 其他 > 详细

Leetcode Balanced Binary Tree

时间:2015-04-11 13:10:23      阅读:123      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!