原题如下:
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.
思路:该题的本质就是一个先序遍历,但在遍历时应该返回左右子树的最小长度,所以在初始时应将minCount设为较大的一个数。另外,叶节点的判断是左右子树都为空,所以切记递归结束条件的判断。另外还是要深刻理解递归算法,包括先序遍历,中序遍历和后序遍历。 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;
int minCount = 65535;
int count = 1;
return countDepth(root,count,minCount);
}
int countDepth(TreeNode *root,int count,int minCount){
if(root->left == NULL && root->right == NULL ){
if(count < minCount)
minCount = count;
return minCount;
}
int count1 = 65535 ,count2 = 65535;
if(root->left !=NULL)
count1 = countDepth(root->left,count + 1,minCount);
if(root->right != NULL)
count2 = countDepth(root->right,count + 1,minCount);
return count1 < count2 ? count1:count2;
}
};
PS(2014.10.09):今天复习此题,发现上述代码思路不够简洁,优化后的代码如下:
int minDepth(TreeNode *root) {
if(root == NULL)
return 0;
if(root->left == NULL && root->right == NULL)
return 1;
int d1= 65535,d2 = 65535;
if(root->left != NULL)
d1 = minDepth(root->left) +1;
if(root->right != NULL)
d2 = minDepth(root->right) +1;
return d1< d2?d1:d2;
}