您的位置:首页 > 其它

Leet Code OJ 110. Balanced Binary Tree [Difficulty: Easy]

2016-03-16 14:02 288 查看
题目:

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.

翻译:

给定一个二叉树,检测它是否是高度平衡的。

这个问题中,一个高度平衡的二叉树是定义在一个二叉树上,它的每个节点的两棵子树的高度相差都不超过1。

分析:

这其实就是判断是否是平衡二叉树。

平衡二叉树,又称***L树。它或者是一棵空树,或者是具有下列性质的二叉树:它的左子树和右子树都是平衡二叉树,且左子树和右子树的高度之差之差的绝对值不超过1。

下面的做法,递归遍历每个节点,每次递归,都获取左右子树的高度进行判断,采用-1作为已经检测到不平衡的标志位,其余情况返回当前子树的高度,用作上一层递归判断。

代码:

[code]/**
 * 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) {
        int depth=getDepth(root,0);
        return depth!=-1;//-1代表子树出现不平衡
    }
    public int getDepth(TreeNode root,int length){
        if(root==null){
            return length;
        }
        int leftDepth=getDepth(root.left,length+1);
        int rightDepth=getDepth(root.right,length+1);
        if(leftDepth==-1||rightDepth==-1||leftDepth-rightDepth>1||rightDepth-leftDepth>1){
            return -1;
        }
        return leftDepth>rightDepth?leftDepth:rightDepth;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: