Get idea from Code Ganker′s Solution
Question
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.
Hide Tags Tree Depth-first Search
Analysis
We need to return the depth of each node and whether it is balanced.
The tricky here is to set -1 if subtree is not balanced, otherwise return depth of root of subtree.
Other′s Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {boolean}
def isBalanced(self, root):
return self.search(root)>=0
def search(self,root):
if root==None:
return 0
hl = self.search(root.left)
hr = self.search(root.right)
if hl>=0 and hr>=0 and abs(hl-hr)<=1:
return 1 + max(hl,hr)
else:
return -1