繁体   English   中英

二叉树的最小深度 Python 不工作

[英]Minimum Depth Of Binary Tree Python Not Working

我正在尝试解决需要找到二叉树的最小深度的问题。 我似乎找不到错误。 任何建议都会有很大帮助。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        
        queue = []
        queue = collections.deque(queue)
        queue.append(root)
        depth = 0
        
        while len(queue) != 0:
            numberOfNodes = len(queue)
            
            while numberOfNodes > 0:
                currentNode = queue.popleft()
                
                if not currentNode and not currentNode:
                    depth += 1
                    return depth
                
                if currentNode.left:
                    queue.append(currentNode.left)
                
                if currentNode.right:
                    queue.append(currentNode.right)
                
                numberOfNodes -= 1
            
            depth += 1
        return depth    

我想我发现了轻微的错误。 代替:

if not currentNode and not currentNode:
    depth += 1
    return depth

也许,应该是这样的:

if currentnode.left is None and currentnode.right is None:     
    return depth

暂无
暂无

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

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