二叉树的三种遍历方式及其分析
文章目录
1,查找的两种方式
![](https://img-blog.csdnimg.cn/20210321140003295.png)
2,静态查找的方式:
![](https://img-blog.csdnimg.cn/20210321140026231.png)
时间复杂度为O(n)。运气好第一个是,运气不好最后一个是,平均时间复杂度是O(N/2)。
-
B 二分查找(Binary Search)
前提:数组中有序存放
对于大数量的查找来说,二分查找的效率会高很多,比如有100万根电线杆,需要找出其中故障的电线杆,那么利用顺序查找平均需要50万次,而利用二分查找平均只需要
log 2 1000000 \log_2 1000000 log21000000
,便是20次,可以看到搜索效率大大提高。
![](https://img-blog.csdnimg.cn/2021032114004761.png)
二分查找启示?-引出树
![](https://img-blog.csdnimg.cn/20210321140100241.png)
3,树的概念
![](https://img-blog.csdnimg.cn/20210321140136966.png)
![](https://img-blog.csdnimg.cn/2021032114020364.png)
4,树的表示
![](https://img-blog.csdnimg.cn/2021032114022364.png)
5,特殊二叉树
![](https://img-blog.csdnimg.cn/20210321140314609.png)
![](https://img-blog.csdnimg.cn/20210321140325244.png)
6,二叉树的重要性质
![](https://img-blog.csdnimg.cn/2021032114042161.png)
![](https://img-blog.csdnimg.cn/20210321140430543.png)
可以通过自上而下和自下而上边相等来证明。
7,二叉树的抽象数据类型和遍历
![](https://img-blog.csdnimg.cn/20210321140449237.png)
7-1,前序遍历
递归的方式:
这里的访问就是打印出来
![](https://img-blog.csdnimg.cn/20210321140505387.png)
途中沿固定的轨迹,是第一次碰到结点时,执行弹出操作,而中序遍历是沿轨迹第二次碰到结点时,执行弹出操作。
C++类的实现:
class Solution {
public:
void preorder(TreeNode* root, vector<int> &res ){
if(root == nullptr)
return;
res.push_back(root->val);
preorder(root->left, res);
preorder(root->right, res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(root, res);
return res;
}
};
非递归循环遍历:
相比于中序遍历,就是第一次碰到它时,就是第一碰到时打印出来。
![](https://img-blog.csdnimg.cn/20210321140524112.png)
C++类的实现:
算法过程:
1,当根节点不为空时,将根节点压入堆栈中;
2,当堆栈不为空时,将栈顶元素弹出,并且分别将此结点的右结点和左结点压入堆栈,这里由于栈是先进后出的,所以先将右结点压入,再压入左结点。
重复上述过程,结束条件每次弹出栈顶元素,压入左右结点,当栈为空时,退出。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int>