
Problem Description:
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.
题目大意:
给定一棵树,找出它从根节点到某一叶子节点的最短路径。
Solutions:
这道题和找出最长路径的做法不太一样。不能直接取左右较短者加一,因为有可能某个子树是空的。细心判断即可。
Code in C++:
/**
* 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) return 0;
int minl = minDepth(root->left);
int minr = minDepth(root->right);
int minx = min(minl,minr);
minx==0?minx=minl+minr:minx=minx;
return minx+1;
}
};




近期评论