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就ok。具体看代码
代码:
/**
* 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==NULL)return 0; //树为空返回0;
if(root->left==NULL&&root->right==NULL) //左右子树都为空,返回1
return 1;
else if(root->left==NULL&&root->right) //左子树为空,右子树不为空的情况
return 1+minDepth(root->right);
else if(root->right==NULL&&root->left) //右子树为空,左子树不为空的情况
return 1+minDepth(root->left);
else if(root->left&&root->right) //左右子树都不为空
return 1+min(minDepth(root->left),minDepth(root->right)); //返回每个节点的最小深度,然后加上根节点
}
};