我是靠谱客的博主 花痴寒风,这篇文章主要介绍C++实现——二叉树的四种遍历(非递归写法),现在分享给大家,希望可以做个参考。

这里写图片描述

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <iostream> #include <vector> #include <stack> #include <queue> using namespace std; //结构体定义如下 typedef struct TreeNode{ //权值 int val; //左右孩子 TreeNode* left, *right; //构造函数 TreeNode() :left(NULL), right(NULL), val(0){} TreeNode(int val) :left(NULL), right(NULL), val(val){} }TreeNode; //二叉树的四种遍历(先序、中序、后序、层次) //层次遍历 vector<int> layerTravel(TreeNode* root){ vector<int> res; if (root == NULL)return res; queue<TreeNode*> q; q.push(root); while (!q.empty()){ //计算当前队列中含有多少元素 int size = q.size(); //从头部依次取出size个元素 for (int i = 0; i < size; i++){ root = q.front(); q.pop(); res.push_back(root->val); //将下一层的元素塞入队列 if (root->left)q.push(root->left); if (root->right)q.push(root->right); } } return res; } //先序和中序存在极大的相似性 //先序遍历 vector<int> preOrderTravel(TreeNode* root){ vector<int> res; if (root == NULL)return res; stack<TreeNode*> s; while (root || !s.empty()){ while (root){ res.push_back(root->val); s.push(root); root = root->left; } root = s.top(); s.pop(); root = root->right; } return res; } //中序遍历 vector<int> inorderTravel(TreeNode* root){ vector<int> res; if (root == NULL)return res; stack<TreeNode*>s; while (root || !s.empty()){ while (root){ s.push(root); root = root->left; } root = s.top(); s.pop(); res.push_back(root->val); root = root->right; } return res; } //后续遍历 vector<int> postOrderTravel(TreeNode* root){ vector<int> res; if (root == NULL)return res; stack<TreeNode*> s; s.push(root); TreeNode* head = root; while (!s.empty()){ TreeNode* t = s.top(); if (!t->left&&!t->right || t->left == head || t->right == head){ res.push_back(t->val); s.pop(); head = t; } else{ if (t->right)s.push(t->right); if (t->left)s.push(t->left); } } return res; } int main(){ return 0; }

最后

以上就是花痴寒风最近收集整理的关于C++实现——二叉树的四种遍历(非递归写法)的全部内容,更多相关C++实现——二叉树内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(57)

评论列表共有 0 条评论

立即
投稿
返回
顶部