这题是判断是否是一个平衡树。我做的方法应该是能出来结果的最慢的了
。多算了好多次高度,方向应该是自下而上,而我是自上而下,所以时间上耗费太多。回头再考虑改进下。代码如下:
。多算了好多次高度,方向应该是自下而上,而我是自上而下,所以时间上耗费太多。回头再考虑改进下。代码如下:# 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
本文介绍了一种判断二叉树是否为平衡树的方法。通过自上而下的递归方式计算每个节点的高度,并检查左右子树高度差是否不超过1来确定整棵树是否平衡。文章最后提出该方法效率较低,有待改进。
263

被折叠的 条评论
为什么被折叠?



