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.
Subscribe to see which companies asked this question.
这道题还是dfs算法。首先是分情况讨论,然后当节点的左右子树都不为空时,要进行递归,分别对左右子节点进行递归,求左右子节点的最小距离。
代码如下:
/**
* 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;
else if(!root->left&&!root->right){
return 1;
}
else{
int l,r;
if(root->left)
l=minDepth(root->left);
else{
l=INT_MAX;
}
if(root->right)
r=minDepth(root->right);
else{
r=INT_MAX;
}
return min(l,r)+1;
}
}
};