这题是判断是否是一个平衡树。我做的方法应该是能出来结果的最慢的了
。多算了好多次高度,方向应该是自下而上,而我是自上而下,所以时间上耗费太多。回头再考虑改进下。代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
#统计节点深度
def numofnode(root):
if root == None:
return 0
global num
num = 0
def priorder(root):
if not root:
return 0
return num + 1 + max(priorder(root.left), priorder(root.right))
return priorder(root)
#判断一个节点是否符合
def nodetrue(root):
if not root:
return True
numofleft = numofnode(root.left)
numofright = numofnode(root.right)
# print numofright, numofleft
if abs(numofright - numofleft) <= 1:
return True
else:
return False
#对每个节点进行判断
result = nodetrue(root)
# print result
if result == False:
return False
boo1 = True
boo2 = True
if root:
if root.left:
boo1 = self.isBalanced(root.left)
if root.right:
boo2 = self.isBalanced(root.right)
return boo1 and boo2