DFS
从上而下
class Solution:
def maxDepth(self, root: TreeNode) -> int:
def helper(root: TreeNode, res: int):
if not root: return res
res += 1
return max(helper(root.left, res), helper(root.right, res))
return helper(root, 0)
从下而上 | Divide & Conquer 分治法
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root: return 0
return 1 + max(self.maxDepth(root.right), self.maxDepth(root.left))
KEY: DFS 深度搜索(从上到下) 和分治法区别:前者一般将最终结果通过指针参数传入,后者一般递归返回结果最后合并
BFS
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root: return 0
stack = [root]
res = 0
while stack:
size = len(stack)
for i in range(size):
top = stack.pop(0)
if top.right:
stack.append(top.right)
if top.left:
stack.append(top.left)
res += 1
return res