We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 1c401fb commit 3f898b4Copy full SHA for 3f898b4
problems/minimum-depth-of-binary-tree.py
@@ -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