forked from greyireland/algorithm-pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.cpp
More file actions
98 lines (88 loc) · 2.26 KB
/
Copy pathtree.cpp
File metadata and controls
98 lines (88 loc) · 2.26 KB
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
#include <algorithm>
#include <stack>
using namespace std;
// 二叉树的前中后序遍历
// 二叉树和链表的转换
template <typename T> struct treeNode{
T val;
treeNode* left;
treeNode* right;
treeNode* parent;
};
// 前序
//递归
template <typename T>
void preOrderRecursion(treeNode<T>* root){
if (root == nullptr) return;
cout<<root->val<<" "<<endl;
preOrderRecursion(root->left);
preOrderRecursion(root->right);
}
void preOrder(treeNoder<T>* root){
if (root == nullptr) return;
stack<treeNode<T>*> treeStack;
treeStack.push(root);
while(!treeStack.empty()){
treeNode* node = treeStack.pop();
if(node->right != nullptr) treeStack.push(node->right);
if(node->left != nullptr) treeStack.push(node->left);
}
}
// 中序
template <typename T>
void inOrderRecursion(treeNode<T>* root){
if (root == nullptr) return;
inOrderRecursion(root->left);
cout<<root->val<<endl;
inOrderRecursion(root->right);
}
template <typename T>
void inOrder(treeNode<T>* root){
if (root == nullptr) return;
stack<treeNode<T>*> S;
while(true){
if(root != nullptr){
S.push(root);
root = root->left;
}
else if(!S.empty()){
treeNode<T>* root = S.pop();
cout<<root->val<<endl;// 访问祖先节点
root = root->right; //遍历右子树
}
else break;
}
}
//后续
// 递归
template <typename T>
void postOrder(treeNode<T>* root){
if(root == nullptr) return;
postOrder(root->left);
postOrder(root->right);
cout<<root->val<<endl;
}
// 迭代
vector<int> postorderTraversal(TreeNode* root) {
if (root == nullptr) return {};
stack<TreeNode*> stk;
stk.push(root);
vector<int> res;
while (!stk.empty()) {
TreeNode* node = stk.top();
if (node == nullptr) {
stk.pop();
res.push_back(stk.top()->val);
stk.pop();
continue;
}
stk.push(nullptr);
if (node->right) {
stk.push(node->right);
}
if (node->left) {
stk.push(node->left);
}
}
return res;
}