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

leetCode 110.Balanced Binary Tree (平衡二叉树) 解题思路和方法

时间:2015-08-05 14:59:59      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:dfs   遍历   二叉树   leetcode   搜索   

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.

思路:判断是否是平衡二叉树,dfs即可,递归判断每个子树是否平衡二叉树,如果有子树不满足,则整体也不满足。

具体代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * 判断是否平衡二叉树
     * 看左右子树高度差是否超过1
     * 不超过1则分别判断左右子树是否平衡二叉树
     */ 
    public boolean isBalanced(TreeNode root) {
        if(root == null)
            return true;
        if(dep(0,root) > - 10)
        	return true;
        return false;
    }
    //计算树的高度
    private int dep(int dep,TreeNode root){
        if(root == null){
            return dep-1;
        }
        int dep1 = dep(dep+1,root.left);
        int dep2 = dep(dep+1,root.right);
        //如果高度差超过1,返回-10
        //则以后的dep返回值均为-10
        if(Math.abs(dep1 - dep2) > 1){
        	return -10;
        }
        return dep1 > dep2 ? dep1 : dep2;
    }
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

leetCode 110.Balanced Binary Tree (平衡二叉树) 解题思路和方法

标签:dfs   遍历   二叉树   leetcode   搜索   

原文地址:http://blog.csdn.net/xygy8860/article/details/47295467

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