[LeetCode]Balanced Binary Tree,解题报告

原创 2013年12月02日 10:21:06

题目

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

其次,理解题目后,很容易想到这是一道典型的递归题目(ps:特别是面试的时候,二叉树和递归联系的特别多,我面试豌豆荚也是考了一个类似的题目)

最后,首先判断根节点的左右子树高度差,相差大于1返回false,相差不大于1则继续递归的测试根节点的左子树和右子树


AC代码


public class BalancedBinaryTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int x) {
            this.val = x;
        }
    }

    public static boolean isBalanced(TreeNode root) {
        if (root == null) return true;

        int lh = getHeight(root.left);
        int rh = getHeight(root.right);

        if (Math.abs(lh - rh) > 1) return false;

        return isBalanced(root.left) && isBalanced(root.right);
    }

    public static int getHeight(TreeNode root) {
        if (root == null) return 0;

        return Math.max(getHeight(root.left), getHeight(root.right)) + 1;

    }
}


吐槽

csdn神马时候才能支持markdown语法编辑博客啊,如果到过年还不支持markdown,果断迁移到segmentfault上了
版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

【LeetCode】Balanced Binary Tree 解题报告

【题目】 Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced bi...

【LeetCode】103. Binary Tree Zigzag Level Order Traversal 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51471280Subject 出处:https://leetcode.com/pro...

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

[leetcode] 236. Lowest Common Ancestor of a Binary Tree 解题报告

题目链接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/    Given a binary tree...

[leetcode] 111. Minimum Depth of Binary Tree 解题报告

题目链接:https://leetcode.com/problems/minimum-depth-of-binary-tree/ Given a binary tree, find its min...

【LeetCode】Validate Binary Search Tree 解题报告

今天CSDN博客发生异常,折腾了大半天终于发出了这篇博文。 【题目】 Given a binary tree, determine if it is a valid binary sear...

LeetCode(114) Flatten Binary Tree to Linked List解题报告

Given a binary tree, flatten it to a linked list in-place.For example, Given 1 / \ ...

[Leetcode] 103. Binary Tree Zigzag Level Order Traversal 解题报告

题目: Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, fro...

LeetCode Convert Sorted List to Binary Search Tree 解题报告

从给定的有序链表生成一颗平衡二叉树。 解题思路:最容易想到的就是利用数组生成二叉树的方法,找到中间节点作为二叉树的root节点,然后分别对左右链表递归调用分别生成左子树和右子树。时间复杂度O(N*lg...

[Leetcode] 255. Verify Preorder Sequence in Binary Search Tree 解题报告

题目: Given an array of numbers, verify whether it is the correct preorder traversal sequence of ...

【LeetCode】257. Binary Tree Paths 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51471280Subject 出处:https://leetcode.com/pro...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)