python - 为什么我的二叉树的最大深度解决方案返回的比预期的少一?
问题描述
我正在解决以下 Leetcode 问题: https ://leetcode.com/problems/maximum-depth-of-binary-tree/solution/
它是返回二叉树的最大深度。
这是我的解决方案:
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
stack = [(root, 1)]
curr_depth = 1
while stack:
node, depth = stack.pop()
depth = max(curr_depth,depth)
if node.right:
stack.append((node.right, curr_depth + 1))
if node.left:
stack.append((node.left, curr_depth + 1))
return depth
由于某种原因,输出总是比预期的少一。查看已接受的解决方案,它们看起来与我的非常相似,但我似乎无法找到我的解决方案出错的地方。
解决方案
这有帮助吗?
from typing import Optional
class Solution:
def maxDepth(self, root: TreeNode) -> int:
return self._visit(root, 0)
def _visit(self, node: Optional[TreeNode], depth: int) -> int:
if not node:
return depth
return max(self._visit(node.left, depth + 1), self._visit(node.right, depth + 1))
推荐阅读
- json - Angular 8 Typescript 展平嵌套数组
- mongodb - 如何从状态数组中提取数据
- c - MS VS 代码:C:如何将库(头文件)与 main.c 链接
- postgresql - 如何使用部分字符字段对 PostgreSQL 表进行分区?
- email - 我不确定我的电子邮件是否加密
- python - 在 Python 中访问 Azure API
- go - 解组 yaml
- angular - 角度垫步更改图标颜色
- javascript - Angular / JavaScript 通过 API 调用添加不需要的标签
- javascript - 如何将多个base64值存储到数组中?