先序遍历(DFS)
class Solution:def maxDepth(self, root: TreeNode) -> int:if not root: return 0return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1作者:jyd链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/solution/mian-shi-ti-55-i-er-cha-shu-de-shen-du-xian-xu-bia/来源:力扣(LeetCode)著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
层序遍历(BFS)
class Solution:def maxDepth(self, root: TreeNode) -> int:if not root:return 0queue = [root]res = 0while queue:temp = list()for node in queue:if node.left:temp.append(node.left)if node.right:temp.append(node.right)queue = tempres+=1return res
