Leetcode 111

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011240016/article/details/82980395

问题类型:Easy, BFS

问题描述:

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.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        elements = [[root, 1]]
        record = {}
        depth = 1
        
        while elements != []:
            [cur, depth] = elements.pop(0)
            if cur != None:
                if cur.left == None and cur.right == None:
                    return depth
                elements += [[cur.left, depth + 1], [cur.right, depth + 1]]
        return 0

解决思路:主要逻辑还是通过使用队列进行树的层序遍历,注意,层序即深度。那按照层序遍历的逻辑,从根部开始,节点非空,就把节点的左右子孙加到队列,然后加一个判断,看节点是否为叶子节点。最主要的是,遍历过程中记录一下深度/层序。这就是这类题目的组合逻辑,本身不复杂。

猜你喜欢

转载自blog.csdn.net/u011240016/article/details/82980395
111