问题描述:
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.
这道题注意什么是叶子节点就好,即左右节点均为空。
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int findDepth(struct TreeNode* root,int step){
if(root->left==NULL&&root->right == NULL)
return step+1;
int leftStep = 0;
int rightStep = 0;
if(root->left)
leftStep = findDepth(root->left,step+1);
if(root->right)
rightStep = findDepth(root->right,step+1);
if(leftStep == 0)
return rightStep;
else if(rightStep == 0)
return leftStep;
else
return (leftStep<rightStep)?leftStep:rightStep;
}
int minDepth(struct TreeNode* root) {
if(!root)
return 0;
return findDepth(root,0);
}