111. Minimum Depth of Binary Tree
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
永远渴望,大智若愚(stay hungry, stay foolish)