LeetCode Minimum Depth of Binary Tree

Source: Internet
Author: User

LeetCode Minimum Depth of Binary Tree
LeetCode-solving-Minimum Depth of Binary Tree

Original question

Calculate the minimum height of a binary tree, that is, the number of nodes passing through the path from the root node to the nearest leaf node.

Note:

None

Example:

Input:

    3   / \  9  20    /  \   15   7  / 14

Output: 2

Solutions

You can achieve this through Tree breadth-first Traversal of Binary Tree Level Order Traversal. In the process of breadth-first Traversal, the height of each layer is increased by one. If a node is a leaf node, the current height is the minimum height.

AC Source Code
# Definition for a binary tree node.class TreeNode(object):    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution(object):    def minDepth(self, root):        """        :type root: TreeNode        :rtype: int        """        if root is None:            return 0        depth, curr_level = 0, [root]        while curr_level:            depth += 1            next_level = []            for n in curr_level:                left, right = n.left, n.right                if left is None and right is None:                    return depth                if left:                    next_level.append(left)                if right:                    next_level.append(right)            curr_level = next_level        return depthif __name__ == "__main__":    None

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.