题目要求:输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路:递归问题,判断每一个节点构成的树是否为平衡二叉树,有不是的则记为0,是的则记为1,故最后如果list中有0存在则说明有不是平衡二叉树的节点,则返回false
但是,有重复遍历的节点,复杂度太高了~以后写的时候优化一下
第一次代码:
class Solution:
def TreeDepth(self, root,list_len,list_node):if root:
list_node.append(root)
if root.left:
self.TreeDepth(root.left,list_len,list_node)
if root.right:
self.TreeDepth(root.right,list_len,list_node)
if not root.left and not root.right:
list_len.append(len(list_node))
list_node.pop()
def Judge(self, root,balan_solu):
left_depth,right_depth = 0,0
if root:
if root.left:
list_len = []
list_node = []
self.TreeDepth(root.left,list_len,list_node)
left_depth = max(list_len)
if root.right:
list_len = []
list_node = []
self.TreeDepth(root.right,list_len,list_node)
right_depth = max(list_len)
if abs(left_depth-right_depth)<=1:
balan_solu.append(1)
else:
balan_solu.append(0)
if root.left:
self.Judge(root.left, balan_solu)
if root.right:
self.Judge(root.right, balan_solu)
def IsBalanced_Solution(self, pRoot):
# write code here
balan_solu = []
if pRoot:
self.Judge(pRoot,balan_solu)
if 0 in balan_solu:
return False
else:
return True