leetcode110 Balanced Binary Tree

题目

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.

解题思路

很显然,解这道题需要从得到二叉树的高度的算法修改而来。
获取二叉树的高度的算法:

private int height(TreeNode node) {
        if (node == null) {
            return 0;
        } else {
            int i = height(node.left);
            int j = height(node.right);
            return (i < j) ? j + 1 : i + 1;
        }
    }

只需要修改下,让树的左右子树的高度差大于1时,返回-1.

public class leetcode110 {
    public boolean isBalanced(TreeNode root) {
        int res = helper(root);
        return res != -1;
    }

    private int helper(TreeNode node) {
        if (node == null) {
            return 0;
        } else {
            int i = helper(node.left);
            int j = helper(node.right);
            if (i == -1 || j == -1)
                return -1;
            else {
                if (Math.abs(i - j) > 1) return -1;
                else
                    return Math.max(i, j) + 1;
            }
        }
    }
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kevinjqy/article/details/71268040
文章标签: leetcode
个人分类: 算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭