[leetcode 111] Minimum Depth of Binary Tree
2015-06-28 21:05
393 查看
题目要求:
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>
相关文章推荐
- ASP.NET MVC 技术债务
- C++ STL内部简单细节整理
- HTTP总结
- 【荐】Grand Central Dispatch Tutorial for Swift: Part 1/2
- 小程序[邮箱提取器-EmailSplider]总结
- 黑马程序员——网络编程
- 反转链表
- 字符串转NSDate时间
- LeetCode_Linked List_Linked List Cycle II
- accordion
- css之颜色篇
- 集合类:List、Set、Map
- 实现dup2功能相同的函数
- 黑马程序员——反射
- dev-ops
- 基于逆波兰RPN算法的计算器实现
- JAVA基础--发送Email
- GCD和NSOperationQueue添加依赖的方法
- mp4网页播放代码,有声音无图像的解决办法~
- 黑马程序员——IO流