无聊的刷题笔记

Minimum Depth of Binary Tree

LeetCode 111

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example

Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7

return its minimum depth = 2.

Solution

class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
depth = 0
queue1 = []
queue2 = []
if root:
queue1.append(root)
depth+=1
else:
return 0
while len(queue1)!=0 or len(queue2!=0):
while len(queue1)!=0:
node = queue1.pop(0)
if not node.left and not node.right:
return depth
if node.left:
queue2.append(node.left)
if node.right:
queue2.append(node.right)
depth += 1
while len(queue2)!=0:
node = queue2.pop(0)
if not node.left and not node.right:
return depth
if node.left:
queue1.append(node.left)
if node.right:
queue1.append(node.right)
depth += 1