二叉树的深度
虽然前面已经做了二叉树的深度,仍然不牢固。
剑指offer里面用的是递归的方法。只要的思路就是,左子树和右子树的比较,大的一支加1作为深度。并不是此时右子树的深度就不加一,现在考虑的是该节点的深度,而不是左右子树的,左右子树只是helper。该节点可能也是其他结点的左右结点之一。
借鉴的一个大神的图,很清晰:
也是相当于后序遍历。
def depth(root, num):
if not root:
return num
res1 = depth(root.left, num+1)
res2 = depth(root.right, num+1)
if res1 > res2:
return res1
else:
return res2
def maxdepth(root):
if not root:
return 0
depthleft = maxdepth(root.left)
depthright = maxdepth(root.right)
if depthleft > depthright:
depthleft += 1
return depthleft # return的就是本结点的深度
else:
defpthright += 1
return depthright
平衡二叉树
如果直接套用maxdepth的函数的话,需要对每一个结点都调用一次这个函数,那么很多结点的深度都计算重复了。
改进就是通过后序遍历,也是相当于上面maxdepth一样,记住了深度,依次比较。
在自下而上求每个结点的深度的同时,附带判断一下左右子树的深度差是否大于1。直到判断到根节点,如果都是平衡二叉树,那么就是了。
tips:多层的递归无法中途停止,借助类的self成员变量来保存中途的信息。
class Solution(object):
def isBalanced(self, root): # 记录下每个结点的深度,后序遍历
if not root:
return True
self.sign = True
def maxdepth(root):
if not root:
return 0
nl = maxdepth(root.left)
nr = maxdepth(root.right)
if nl > nr :
if abs(nl-nr)>1:
self.sign = False
nl += 1
return nl
else:
if abs(nl-nr)>1:
self.sign = False
nr += 1
return nr
maxdepth(root)
return self.sign