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

110. Balanced Binary Tree

时间:2016-09-10 06:43:40      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Solution 1:

思路:首先判断root.left和root.right是否有符合条件的depth,加入辅助函数,也就是104的maxdepth,然后再递归检查左子树和右子树。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null)
        {
            return true;
        }
        if(Math.abs(depth(root.left)-depth(root.right))<=1)
        {
            return isBalanced(root.left)&&isBalanced(root.right);
        }
        else
        {
            return false;
        }
    }
        
    public int depth(TreeNode root)
    {
        if(root==null)
        {
            return 0;
        }
        return Math.max(depth(root.left),depth(root.right))+1;
    }
        
    
}

Solution 2: 

discussion看到一种更巧妙的做法:

public boolean isBalanced(TreeNode root) {
    return getDepth(root) != -1;
}

private int getDepth(TreeNode root) {
    if (root != null) {
        int left = getDepth(root.left);
        int right = getDepth(root.right);
        
        return (left == -1 || right == -1 || Math.abs(left-right) > 1) ? -1 : Math.max(left, right) + 1;
    }
    
    return 0;
}

Define a getDepth method, which will return the height of the tree, if it is balanced, otherwise, return -1.

定义的这个getDepth行使两个功能,一是记录depth如果balanced,二是记录-1如果不balanced。

定义好一个recursion的函数很重要啊!!

110. Balanced Binary Tree

标签:

原文地址:http://www.cnblogs.com/Machelsky/p/5858612.html

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