[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;
}
};
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;
}
};
相关文章推荐
- leetcode 654. Maximum Binary Tree
- [Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree
- LeetCode-104. Maximum Depth of Binary Tree
- 第十八周:[Leetcode]111. Minimum Depth of Binary Tree
- LeetCode 226. Invert Binary Tree (反转二叉树)
- [Leetcode] Binary tree--653. Two Sum IV
- leetcode记录 104. Maximum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- python--leetcode226. Invert Binary Tree
- Leetcode 104. Maximum Depth of Binary Tree
- leetcode 104. Maximum Depth of Binary Tree
- 【Leetcode】111. Minimum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- [Leetcode] Binary tree-- 637. Average of Levels in Binary Tree
- [LeetCode] 111. Minimum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- [leetcode: Python]104. Maximum Depth of Binary Tree
- leetcode--111. Minimum Depth of Binary Tree
- 渣渣写LEETCODE——104. Maximum Depth of Binary Tree
- Leetcode 104. Maximum Depth of Binary Tree