二叉树最小深度探究
来源:互联网 发布:淘宝店铺重开 编辑:程序博客网 时间:2024/05/20 05:30
一、求解最小深度
题目是这样描述的: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.
采用两种方法解答:递归和非递归的方法
1、采用递归的方法:
class Solution {public: int run(TreeNode *root) { if(root == NULL) return 0; if(root->left == NULL && root->right == NULL) return 1; int leftDepth = run(root->left); if(leftDepth == 0) leftDepth = INT_MAX;//防止左孩子为空,带来的影响 int rightDepth = run(root->right); if(rightDepth == 0) rightDepth = INT_MAX;//防止右孩子为空,带来的干扰 return leftDepth < rightDepth ? (leftDepth + 1) : (rightDepth + 1); }};//另外一种写法:class Solution {public: int minDepth(TreeNode *root) { if (root == NULL) return 0;//根节点为空的情况 if (root->left == NULL && root->right == NULL) return 1;//没有左右孩子的情况 if (root->left == NULL) return minDepth(root->right) + 1;//没有左孩子,只有右孩子的情况。 else if (root->right == NULL) return minDepth(root->left) + 1;//没有右孩子,只有左孩子的情况。 else return 1 + min(minDepth(root->left), minDepth(root->right));//正常的情况 }};
2、非递归的方法
//层次遍历,先增加push,后删除pop.每遍历一层deepth增加1class Solution {public: int run(TreeNode *root) { queue<TreeNode*> q; if(root==NULL) return 0; q.push(root); int deepth=0; while(!q.empty())//构成一个循环 { int len=q.size(); deepth++; while(len--)//内循环用来删除父节点,增加子节点 { TreeNode *tmp=q.front(); q.pop(); if(tmp->left!=NULL) q.push(tmp->left); if(tmp->right!=NULL) q.push(tmp->right); if(tmp->right==NULL && tmp->left==NULL) return deepth; } } return deepth; }};
参考几位大佬的链接如下,感谢各位大佬的博客:
1、http://www.cnblogs.com/grandyang/p/4042168.html
2、http://www.cnblogs.com/felixfang/p/3887565.html
3、http://blog.csdn.net/fisherming/article/details/75096410(二叉树求深度的递归的详细分析,大佬关于递归调用的详解)
4、http://blog.csdn.net/brucehb/article/details/47453415
阅读全文
0 0
- 二叉树最小深度探究
- 二叉树最小深度
- 二叉树最大 最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- leetcode 二叉树最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 求二叉树最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- 二叉树的最小深度
- jsp基础-九大内置对象
- 实验一:Linux操作系统的安装
- Hdu1969-Pie-【二分】
- RGBD_SLAM(1)
- 八种架构设计模式及其优缺点概述
- 二叉树最小深度探究
- BeautifulSoup中的.text方法和get_text()方法的区别
- 2-sat
- 浅谈八皇后问题
- 某笔试题(一)获取20个随机不重复的字符
- JavaWeb
- Spring bean id相同引发的故障
- demo_3. Python的函数嵌套
- nodejs和python 简单爬取百度图片保存在本地