File tree Expand file tree Collapse file tree 1 file changed +13
-8
lines changed Expand file tree Collapse file tree 1 file changed +13
-8
lines changed Original file line number Diff line number Diff line change 1
- def minDepth ( self , root ):
2
- """
3
- :type root: TreeNode
4
- :rtype: int
5
- """
6
- queue = [ root ]
7
- current = []
8
- mindepth = 0
1
+ #Question: Given the root of a tree, find the minimum dept the tree goes
2
+ #Solution: Use a BFS traversal to find the first leaf node of the tree
3
+ #Difficulty: Easy
4
+
5
+ def minDepth ( root ):
6
+ #Define queue, current queue and a mindepth variable
7
+ queue = [ root ]; current = []; mindepth = 0
8
+ #If our current node is null, the depth is 0, so return 0
9
9
if not root : return mindepth
10
+ #As long as our queue exists
10
11
while queue :
12
+ #For every element in our queue
11
13
for i in queue :
14
+ #If we have reached a leaf node, we can return 1+mindepth
12
15
if not i .left and not i .right : return mindepth + 1
16
+ #Else we append the left and right children to our queue (See BFS traversal)
13
17
if i .left : current .append (i .left )
14
18
if i .right : current .append (i .right )
19
+ #Set queue to current queue, current to empty list and add one to our mindepth because we're now on a new level
15
20
queue = current
16
21
current = []
17
22
mindepth += 1
You can’t perform that action at this time.
0 commit comments