LintCode Q93 Balanced Binary Tree in Python

  • Jinhai ZHOU
  • 5 Minutes
  • 2016年11月15日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
import sys
class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
if root is None:
return True
left_height = self.countHeight(root.left)
right_height = self.countHeight(root.right)
if left_height == sys.maxint or right_height == sys.maxint:
return False
if abs(left_height - right_height) <= 1:
return True
else:
return False
def countHeight(self, root):
if root is None:
return 0
left_height = self.countHeight(root.left)
right_height = self.countHeight(root.right)
if left_height == sys.maxint or right_height == sys.maxint:
return sys.maxint
if abs(left_height - right_height) > 1:
return sys.maxint
else:
return max(left_height, right_height) + 1
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。