【问题标题】:Problem with Minimum Depth of Binary Tree二叉树的最小深度问题
【发布时间】:2021-07-30 16:13:16
【问题描述】:

谁能帮我弄清楚我的代码有什么问题?

这个测试用例不起作用 - [2,null,3,null,4,null,5,null,6] - 我的代码返回 0 而不是 5。不知道为什么。

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if root.left is None and root.right is None:
            return 0
        elif root.left is None and root.right is not None:
            return self.minDepth(root.right)
        elif root.right is None and root.left is not None:
            return self.minDepth(root.left)
        else:
            return 1 + min(self.minDepth(root.left), self.minDepth(root.right))

谢谢!

【问题讨论】:

  • 为什么在所有情况下都不给递归调用加 1?
  • 如果您只是调试并单步执行代码,并查看变量具有函数调用返回的值,这将很容易解决。一旦你这样做了,你就会发现没有理由发布这个问题。

标签: python recursion binary-tree


【解决方案1】:

你应该首先检查它自己的根,以防输入是一棵空树(根为无)。没有此空检查,您将获得 NPE。和你 还需要在 elif 块中包含当前根本身。 这是我接受的代码:

class Solution(object):
    def minDepth(self, root):
        if root is None:
            return 0
        elif root.left is None and root.right is not None:
            return self.minDepth(root.right) + 1
        elif root.right is None and root.left is not None:
            return self.minDepth(root.left) + 1
        else:
            return 1 + min(self.minDepth(root.left), self.minDepth(root.right))

【讨论】:

  • 刚把解决方案改成python版本
  • 天啊!太感谢了。如果您有更好的解决方案,请告诉我:)
猜你喜欢
  • 2014-08-07
  • 2016-01-24
  • 2021-09-19
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多