【日更 Day23】Leetcode 111

问题类型: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

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

END.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容