本文共 979 字,大约阅读时间需要 3 分钟。
BFS
# Definition for a binary tree node.class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 q = [] q.append(root) ans = 0 while q: tmp = [] for i in q: if i.left: tmp.append(i.left) if i.right: tmp.append(i.right) ans += 1 q = tmp return ans
递归
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 else: l = self.maxDepth(root.left) + 1 r = self.maxDepth(root.right) + 1 return max(l, r)
转载地址:http://pbrgn.baihongyu.com/