- Minimum Depth of Binary Tree
中文English
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.
Example
Example 1:
Input: {}
Output: 0
Example 2:
Input: {1,#,2,3}
Output: 3
Explanation:
1
\
2
/
3
it will be serialized {1,#,2,3}
Example 3:
Input: {1,2,3,#,#4,5}
Output: 2
Explanation:
1
/ \
2 3
/
4 5
it will be serialized {1,2,3,#,#,4,5}
解法1:DFS。
注意,直接写成
int minDepth(TreeNode * root) {
if (!root) return 0;
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
不对,因为1,#,3这样的情况会返回1。
代码如下:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree
* @return: An integer
*/
int minDepth(TreeNode * root) {
if (!root) return 0;
if (!root->left) return minDepth(root->right) + 1;
if (!root->right) return minDepth(root->left) + 1;
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
};
二刷:
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) return 0;
helper(root, 0);
return min_depth;
}
void helper(TreeNode* root, int depth) {
if (!root) return;
depth++;
if (!root->left && !root->right) {
min_depth = min(min_depth, depth);
return;
}
helper(root->left, depth);
helper(root->right, depth);
depth--;
}
private:
int min_depth = INT_MAX;
};
也可以
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) return 0;
helper(root, 1);
return min_depth;
}
void helper(TreeNode* root, int depth) {
if (!root) return;
if (!root->left && !root->right) {
min_depth = min(min_depth, depth);
return;
}
helper(root->left, depth + 1);
helper(root->right, depth + 1);
}
private:
int min_depth = INT_MAX;
};