110. Balanced Binary Tree(平衡树判断)

2,397次阅读

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.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

3
/ \
9  20
/  \
15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

1
/ \
2   2
/ \
3   3
/ \
4   4

Return false.

104. Maximum Depth of Binary Tree

class Solution(object):
def maxDepth_gd(self, root):
'''bugfree'''
if not root: return 0

left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left, right) + 1

class Solution(object):
def isBalanced(self, root):
if not root: return True
left = self.get_height(root.left)
right = self.get_height(root.right)
if abs(left - right) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)

def get_height(self, root):
if not root: return 0
left = self.get_height(root.left)
right = self.get_height(root.right)
return max(left, right) + 1


# Recursive Rules:
# 索取：Node的左孩子是不是全部是Balanced，Node的右孩子是不是全部是Balanced的，
# 返回：如果都是Balanced的，返回True，不然返回False

class Solution(object):
def isBalanced(self, root):
self.flag = False
self.getHeight(root)
return not self.flag

def getHeight(self, root):
if not root: return 0
left = self.getHeight(root.left)
right = self.getHeight(root.right)
if abs(left - right) > 1:
self.flag = True
return max(left, right) + 1