题目描述
求给定二叉树的最大深度。最大深度是指树的根结点到最近叶子结点的最长路径上结点的数量。
1(最初劣质版)
思路
遍历所有从根节点到叶子节点的路径,求最长
- 当栈顶左子树右子树均为空时→叶子节点:如果长度大于最长长度则记为最长长度,否则退回父节点,并进入废弃数组
- 当栈顶左子树不为空且左儿子不在废弃数组:左儿子入栈
- 当栈顶右子树不为空且右儿子不在废弃数组:右儿子入栈
- 当栈顶左子树右子树均不为空但均在废弃数组时:出栈
class Solution:
def maxDepth(self , root ):
# write code here
if not root:
return 0
pstack = [root]
used = []
result = 1
while pstack:
if pstack[-1].left==None and pstack[-1].right==None:#leaf
if len(pstack) > result:
result = len(pstack)
tmp = pstack.pop(-1)
used.append(tmp)#del
elif pstack[-1].left is not None and pstack[-1].left not in used:
pstack.append(pstack[-1].left)
elif pstack[-1].right is not None and pstack[-1].right not in used:
pstack.append(pstack[-1].right)
else:
tmp = pstack.pop(-1)
used.append(tmp)#del
return result
2(层次遍历)
思路
层次遍历,返回树深度
def run(self , root ):
# write code here
if not root:return 0
level = [root]
result = 0
tmp = []
while level:
i = level.pop(0)
if i.left:tmp.append(i.left)
if i.right:tmp.append(i.right)
if not level:
level = tmp.copy()
result += 1
tmp = []
return result
3(递归)
class Solution:
def maxDepth(self , root ):
# write code here
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))