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即可,但要注意当没有左子树/右子树时,要计算另一个节点的深度,因为没有到达leaf节点。
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
if(!root->left) return 1+minDepth(root->right);
if(!root->right) return 1+minDepth(root->left);
return 1 + min(minDepth(root->left), minDepth(root->right));
}
};