问题来自美团笔试
输入一行表示节点数,接下来输入边,求从根节点访问所有节点的最短路径。
1
/ \
2 3
/ \
4 5
\
6
最短路径为:1-2-1-3-4-3-5-6
.
思路
递归:
int minDepth(TreeNode* root){
if(!root)
return 0;
else{
int leftDepth = minDepth(root->left);
int rightDepth = minDepth(root->right);
return leftDepth<rightDepth?leftDepth+1:rightDepth+1;
}
}