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.
题目:二叉树的最小深度。从根结点到叶节点。
思路:同104. Maximum Depth of Binary Tree。
/**
* 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:
int minDepth(TreeNode* root) {
if(root == nullptr)
return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
// 注意这里需要判断是否为空的情况,同maxDepth的区别
if(left == 0 || right == 0)
return left + right + 1;
else
return min(left, right) + 1;
}
};