Update 0102.二叉树的层序遍历.md

This commit is contained in:
jianghongcheng
2023-05-03 20:13:38 -05:00
committed by GitHub
parent 6117327718
commit de7c67c35a

View File

@ -2938,23 +2938,26 @@ Python 3
# self.right = right
class Solution:
def minDepth(self, root: TreeNode) -> int:
if root == None:
if not root:
return 0
depth = 0
queue = collections.deque([root])
while queue:
depth += 1
for _ in range(len(queue)):
node = queue.popleft()
if not node.left and not node.right:
return depth
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
#根节点的深度为1
queue_ = [(root,1)]
while queue_:
cur, depth = queue_.pop(0)
if cur.left == None and cur.right == None:
return depth
#先左子节点,由于左子节点没有孩子,则就是这一层了
if cur.left:
queue_.append((cur.left,depth + 1))
if cur.right:
queue_.append((cur.right,depth + 1))
return 0
return depth
```
Go