第一反应:拿到这个题,一看深度,就往层遍历上面去想!!!!这里给出两种解决方案,第二种允许你想不到,但是第一种,你看这个题目你就应该想到!!!!!
强调一下:层次遍历的代码,希望大家背下来。就跟你小学写作文一样的东西【万金油】代码
【万金油代码】
########### 【层次遍历】#########
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
stack1 = [root]
stack2 = []
ret = []
while stack1 or stack2:
if stack1:
tmpList = []
while stack1:
tmp = stack1[0]
tmpList.append(tmp.val)
if tmp.left:
stack2.append(tmp.left)
if tmp.right:
stack2.append(tmp.right)
del stack1[0]
ret.append(tmpList)
if stack2:
tmpList = []
while stack2:
tmp = stack2[0]
tmpList.append(tmp.val)
if tmp.left:
stack1.append(tmp.left)
if tmp.right:
stack1.append(tmp.right)
del stack2[0]
ret.append(tmpList)
return len(ret)
########### 【递归思想】#########
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1