您的位置:首页 > 其它

[leetcode]111. Minimum Depth of Binary Tree

2016-11-07 00:17 351 查看
题目链接:https://leetcode.com/problems/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.

方法1:
class Solution{
public:
int minDepth(TreeNode * root)
{
if(root==NULL) return 0;
int mark=INT_MAX;

preTraverse(root, 1, mark);
return mark;
}

void preTraverse(TreeNode * root,int depth,int &mark)
{
if(root==NULL) return;
if(root->left==NULL && root->right==NULL)
{
if(depth<mark)
mark=depth;
}
preTraverse(root->left, depth+1,mark);
preTraverse(root->right, depth+1,mark);
}
};


方法2:
class Solution {
public:
int minDepth(TreeNode *root) {
if(root==NULL)
return 0;
int mleft=minDepth(root->left);
int mright=minDepth(root->right);
if(mleft==0)
return 1+mright;
else if(mright==0)
return 1+mleft;
else return min(mleft,mright)+1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: