码迷,mamicode.com
首页 > 其他好文 > 详细

111. Minimum Depth of Binary Tree

时间:2018-12-09 20:01:10      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:obj   minimum   test   from   mat   The   bfs   +=   null   

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.

 

Approach #1: C++. [recursive]

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root == NULL) return 0;
        return helper(root, 1);
    }
private:
    int helper(TreeNode* root, int depth) {
        if (root->left != NULL && root->right != NULL)
            return min(helper(root->left, depth+1), helper(root->right, depth+1));
        else if (root->left != NULL) 
            return helper(root->left, depth+1);
        else if (root->right != NULL)
            return helper(root->right, depth+1);
        return depth;
    }
};

  

Approach #2: Java.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        return (left == 0 || right == 0) ? left + right + 1 : Math.min(left, right) + 1;
    }
}

  

Approach #3: Python. [BFS]

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

from Queue import *
class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        
        q = Queue()
        q.put(root)
        
        ans = 0
        
        while not q.empty():
            ans += 1
            k = q.qsize()
            
            for i in range(k):
                
                cur = q.get()

                if cur.left:
                    q.put(cur.left)
                if cur.right:
                    q.put(cur.right)
            
                if cur.left == None and cur.right == None:
                    return ans

  

 

111. Minimum Depth of Binary Tree

标签:obj   minimum   test   from   mat   The   bfs   +=   null   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/10092513.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!