Minimum Depth of Binary Tree and quick sort
来源:互联网 发布:临沂淘宝店铺装修 编辑:程序博客网 时间:2024/04/29 14:55
今日更新主要内容如下: 第一、二叉树求最小二叉树深度。第二、分析快速排序算法。 二叉树部分: 求二叉树最小深度,无非是两种DFS、BFS。我们先来看深度遍历方法。
DFS分析:
1.对比跟节点左右子树深度,最小的那个加1即是最小深度,代码如下:
int minDepth(TreeNode* root){ if(root == NULL) return 0; int depth = 0; if(root->left !=NULL && root->right !=NULL){ int left = minDepth(root->left); int right = minDepth(root->right); depth = left < right? left:right }else if(root->left !=NULL){ depth= minDepth(root->left); }else if(root->right !=NULL){ depth = minDepth(root->right); } return depth + 1;}
注意DFS的递归条件,对比左右子树的深度。
BFS解析:
1,层次遍历法,分层遍历,只要是当前节点的某一个子树为空,可以马上返回,即是最小深度。代码实现(因为需要用到队列,故而用C++代码实现):
class Solution {public: int minDepth(TreeNode* root) { if(root == NULL) return 0; // 用于遍历的队列 queue<TreeNode*> queue; int curNum = 0; int lastnum = 1; int level = 1; queue.push(root); while(queue.size()){ // 取出头节点 TreeNode* cur = queue.front(); // 清楚头结点 queue.pop(); //判断当前节点是否有子节点,若没有直接返回 if(root->left ==NULL && root->right == NULL) return level; lastnum--; if(cur->left !=NULL){ queue.push(cur->left); curNum++; } if(cur->right!=NULL) { queue.push(cur->right); curNum++; } if(lastNum == 0){ lastnum = curNum; curNum = 0; level++; } } return 0; }};
完成了,其实这个题目也是考察的二叉树遍历问题。
再看看快速排序的问题,快速排序思想分析:
1. 找出一个基准数。并准备头尾两个指针对数组进行遍历。
2. 左边的指针i, 往前走当当前位置的数大于基准数时,停止,让后指针J从数组尾部遍历,当当前的数大于基准数时,停止,交互i,j位置的数字。
3. 当i,j相遇时,首先将基准数与当前的i值互换,此时基准数归位。
4. 然后进行递归。
结合代码实现如下:
void quick_sort(int left,int right,int[] num){ if(left > right) return ; int i = left; int j = right; int t = 0; int tmp = num[left]; // 基准数 while(i!=j){ while(j > i && num[j]>= tmp){ j--; } while(j > i && num[i] <= tmp){ i++; } if(i < j) { t = num[i]; num[i] = num[j]; num[j] = t; } } // 基准数归位 a[left] = a[i]; a[i] = tmp; quick_sort(left,i-1,num); quick_sort(i+1,right,num);}
齐活了,今天的数据结构部分的总结到此为止了。
0 0
- Minimum Depth of Binary Tree and quick sort
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- c++作业计算某年某月有多少天,个人所得税计算器,利息计算器
- 2017GMIC科技庙会有什么好玩?
- 异或运算详解
- 第三次上机作业
- 关于rxjava2的CompositeDisposable
- Minimum Depth of Binary Tree and quick sort
- route命令的使用
- mp4 stsd/mp4a/esds 和 mp4 stsd/avc1/avcc
- Android应用程序私有目录下文件操作总结
- 不同直播场景的CDN技术简析
- Mysql 常用sql命令
- 满二叉树和完全二叉树
- php RSA加密解密实例
- pageoffice在Edge浏览器、谷歌浏览器42及以上版本和火狐浏览器52及以上版本兼容处理