首页 > 解决方案 > 为什么我的二叉树的最大深度解决方案返回的比预期的少一?

问题描述

我正在解决以下 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
    

由于某种原因,输出总是比预期的少一。查看已接受的解决方案,它们看起来与我的非常相似,但我似乎无法找到我的解决方案出错的地方。

标签: pythonbinary-tree

解决方案


这有帮助吗?

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))

推荐阅读