先对树的每个节点求高度, 最后判断。
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
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 == None:
return True
L = []
self.pre_order(root, L)
for i in L:
if i > 1:
return False
return True
#求每个节点的高度
def tree_depth(self, root):
if root == None:
return 0
l_depth = self.tree_depth(root.left)
r_depth = self.tree_depth(root.right)
return (l_depth + 1) if (l_depth > r_depth) else (r_depth + 1)
def pre_order(self, root, L):
if root == None:
return
l_d = self.tree_depth(root.left)
r_d = self.tree_depth(root.right)
L.append(abs(l_d - r_d))
self.pre_order(root.left, L)
self.pre_order(root.right, L)