LeetCode Balanced Binary Tree

Source: Internet
Author: User

LeetCode Balanced Binary Tree
Balanced Binary Tree for solving LeetCode Problems

Original question

Determine whether a binary tree is a balanced binary tree. This tree is balanced only when the height difference between the left and right trees of each node is not greater than 1.

Note:

None

Example:

Input:

    3   / \  9  20    /  \   15   7  / 14

Output: False

Solutions

The height of a node is that the height of the left and right trees is higher than that of the other two trees. To make the code concise, the height of the unbalanced subtree is defined as-1, therefore, when calculating the height of each node, You need to determine whether the left and right decision trees are balanced. If the left decision trees are not balanced, the right decision trees are not balanced. | the left and right decision trees are not balanced. | the height difference between the left and right decision trees is greater than 1) -1 is returned directly.

AC Source Code
# Definition for a binary tree node.class TreeNode(object):    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution(object):    def isBalanced(self, root):        """        :type root: TreeNode        :rtype: bool        """        return self._isBalanced(root) >= 0    def _isBalanced(self, root):        if not root:            return 0        left, right = self._isBalanced(root.left), self._isBalanced(root.right)        if left >= 0 and right >= 0 and abs(left - right) <= 1:            return 1 + max(left, right)        else:            return -1if __name__ == "__main__":    None

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.