【发布时间】:2021-07-26 03:52:06
【问题描述】:
我正在解决以下 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
由于某种原因,输出总是比预期的少一。并且查看接受的解决方案,它们看起来与我的非常相似,但我似乎无法找到我的解决方案出错的地方。
【问题讨论】:
-
您在使用调试器时发现了什么?
-
node, depth = stack.pop()应该是node, curr_depth吗? -
哦,好吧,是的,我现在看到了 jamesdlin。
-
@mkrieger1 - 调试器没有显示错误。我在 Pycharm 上运行它
-
感谢 mkrieger1 的链接,我会仔细阅读它们——非常有用!
标签: python binary-tree