最大深度
递归结束的条件是节点为空,返回0
非递归用栈 去深度优先搜索树的所有节点
最小深度
非递归用队列 , 一旦节点没有左右孩子,就结束返回了
class Solution(object):
def maxDepth1(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root==None:
return 0
else:
l = 1 + self.maxDepth(root.left)
r = 1 + self.maxDepth(root.right)
return max(l, r)
def maxDepth(self, root):
stack = []
if root:
stack.append((1,root))
depth = 0
while stack!=[]:
curdepth, root = stack.pop()
if root:
depth = curdepth if curdepth>depth else depth
stack.append((curdepth+1,root.left))
stack.append((curdepth+1,root.right))
return depth
class Solution(object):
def minDepth1(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
if root.left==None and root.right == None:
return 1
elif root.left == None:
return 1 + self.minDepth(root.right)
elif root.right == None:
return 1 + self.minDepth(root.left)
else:
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
def minDepth(self, root):
if root == None:
return 0
if root.left == None and root.right == None:
return 1
queue = [(1,root)]
while queue != []:
curdepth, root = queue.pop(0)
if root.left == None and root.right == None:
return curdepth
if root.left:
queue.append((curdepth+1, root.left))
if root.right:
queue.append((curdepth+1, root.right))