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

[LeetCode]110 Balanced Binary Tree

时间:2015-01-06 15:46:32      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/balanced-binary-tree/

http://blog.csdn.net/linhuanmars/article/details/23731355

/**
 * 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 visit(root).balanced;
    }
    
    /////////////////////////
    // Solution A: DFS
    // 
    // By definition: depth of two subtrees never differ by more than 1.
    private Result visit(TreeNode node)
    {
        if (node == null)
            return new Result(0, true);
            
        Result left = visit(node.left);
        if (!left.balanced)
            return new Result(0, false);
            
        Result right = visit(node.right);
        if (!right.balanced)
            return new Result(0, false);
        
        int height = Math.max(left.height, right.height) + 1;
        boolean balanced = Math.abs(left.height - right.height) <= 1;
        return new Result(height, balanced);
    }
    
    private static class Result
    {
        int height;
        boolean balanced;
        Result(int height, boolean balanced)
        {
            this.height = height;
            this.balanced = balanced;
        }
    }
}


[LeetCode]110 Balanced Binary Tree

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1599703

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