Easy
644322FavoriteShare
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.
C++:
DFS剪枝法:
/*
* @Author: SourDumplings
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/minimum-depth-of-binary-tree/
* @Date: 2019-03-07 20:56:10
*/
/**
* 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:
const int MAX = 99999;
int minDepth(TreeNode *root)
{
if (!root)
{
return 0;
}
int minD = MAX;
dfs(root, 1, minD);
return minD;
}
void dfs(TreeNode *s, int nowD, int &minD)
{
if (!s->left && !s->right)
{
if (nowD < minD)
{
minD = nowD;
}
}
else if (nowD < minD)
{
if (s->left)
{
dfs(s->left, nowD + 1, minD);
}
if (s->right)
{
dfs(s->right, nowD + 1, minD);
}
}
return;
}
};
比较左右子树高度法:
/*
* @Author: SourDumplings
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/minimum-depth-of-binary-tree/
* @Date: 2019-03-07 20:42:14
*/
/**
* 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:
const int MAX = 99999;
int minDepth(TreeNode *root)
{
if (!root)
{
return 0;
}
else if (!root->left && !root->right)
{
return 1;
}
else
{
int l = minDepth(root->left);
int r = minDepth(root->right);
if (l == 0)
{
l = MAX;
}
if (r == 0)
{
r = MAX;
}
return min(l, r) + 1;
}
}
};