Skip to content

Commit 3f898b4

Browse files
author
Chris Wu
committed
no message
1 parent 1c401fb commit 3f898b4

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""
2+
We use BFS, so as soon as we touch a leaf; we can return it.
3+
Because BFS traverse the tree level by level. We can be sure that the first leaf we touch is the nearest leaf.
4+
Note that, a leaf is a node with no children.
5+
"""
6+
from collections import deque
7+
8+
class Solution(object):
9+
def minDepth(self, root):
10+
if not root: return 0
11+
q = deque()
12+
q.append((root, 1))
13+
14+
while q:
15+
node, depth = q.popleft()
16+
if not node.left and not node.right:
17+
return depth
18+
if node.left:
19+
q.append((node.left, depth+1))
20+
if node.right:
21+
q.append((node.right, depth+1))

0 commit comments

Comments
 (0)