题目要求:
Minimum Depth of Binary Tree
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.
最近一直在leetcode上做树相关的题目,自我感觉一直做的不好,或者说思路很不清晰的最主要原因是对于递归的运行机制理解得不透彻,通过这一题有了更近一步的认识。“在递归调用的过程当中系统为每一层的返回点、局部量等开辟了栈来存储。”
代码一:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int min(int a, int b)
{
if (a < b)
return a;
else
return b;
}
int minDepth(struct TreeNode* root) {
if (root == 0)
return 0;
if( root->left ) //判断左子树存在
{
if( root->right ) //判断右子树存在
{
return min(minDepth(root->left), minDepth(root->right)) + 1;
} //当左右子树都存在的时候,在此次设置递归函数断点
else
return minDepth(root->left) + 1; //只存在左子树的时候,设置在此设置递归函数断点
}
else if( root->right )
{
return minDepth(root->right) + 1; //只存在右子树的时候,设置在此设置递归函数断点
}
else
return 1; //左右子树都为空,返回1
}
代码参考自:http://www.julyedu.com/video/play/id/32
代码二:
<span style="font-size:14px;">/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int minDepth(struct TreeNode* root)
{
int left, right; //一开始把这两个变量设置为全局变量的时候出现RA
if(root == 0)
return 0;
if(root->left == 0 && root->right == 0)
return 1;
left = minDepth(root->left) + 1; //左子树设置断点递归
right = minDepth(root->right) + 1;//右子树设置断点递归
if(left == 1)
left = INT_MAX; //当左子树为空时,将它设置为无限大量,剔除干扰
if(right == 1)
right = INT_MAX; //同上
return left < right ? left : right; //返回小的
}
注:INT_MAX 头文件:#include <limits.h>