mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0102.二叉树的层序遍历.md
This commit is contained in:
@ -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:
|
||||
|
Reference in New Issue
Block a user