繁体   English   中英

二叉树的最小深度问题

[英]Problem with Minimum Depth of Binary Tree

有人可以帮我弄清楚我的代码有什么问题吗?

This test case doesn't work - [2,null,3,null,4,null,5,null,6] - my code returns 0 instead of 5. Not sure why.

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

谢谢!

您应该首先检查它自己的根,以防输入是一棵空树(根为无)。 如果没有此 null 检查,您将获得 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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM