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