二叉树的最小深度 - returns None

Minimum Depth of Binary Tree - returns None

我正在研究 LeetCode 问题 111. Minimum Depth of Binary Tree:

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

我使用了广度优先算法并尝试对其进行更改以使其与问题保持一致。但是函数正在返回 None.

谁能解释为什么会这样?

def minDepth(self, root: Optional[TreeNode]) -> int:
        queue=[]
        if root==None:
            return 0
        level=1
        while(len(queue)>0):
            n=len(queue)
            for i in range(n):
                node=queue.pop(0)
                if not node.right and not node.left:
                    return(level)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            level+=1

问题是在循环即将开始时您的队列是空的。

你应该把根节点放在里面:

        if root is None:
            return 0
        queue = [root]  # <----
        level = 1
        while queue:  
            # ...etc