给定一个二叉树,找出其最大深度。python
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。app
说明: 叶子节点是指没有子节点的节点。code
示例:
给定二叉树 [3,9,20,null,null,15,7]
,递归
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。io
利用递归的深度优先搜索class
复杂度分析二叉树
show me the code搜索
class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 else: left_height = self.maxDepth(root.left) right_height = self.maxDepth(root.right) return max(left_height, right_height) + 1
咱们还能够在栈的帮助下将上面的递归转换为迭代。方法
咱们的想法是使用 DFS 策略访问每一个结点,同时在每次访问时更新最大深度。时间
因此咱们从包含根结点且相应深度为 1
的栈开始。而后咱们继续迭代:将当前结点弹出栈并推入子结点。每一步都会更新深度。
复杂度分析
show me the code
class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ stack = [] if root is not None: stack.append((1, root)) depth = 0 while stack != []: current_depth, root = stack.pop() if root is not None: depth = max(depth, current_depth) stack.append((current_depth + 1, root.left)) stack.append((current_depth + 1, root.right)) return depth