遍历二叉树-前/中/后序-递归/非递归

递归方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void preorder(TreeNode* root, vector<int>&path)
{
if (root==nullptr) return;
path.push_back(root->val);
preorder(root->left, path);
preorder(root->right, path);
}
void inorder(TreeNode* root, vector<int>&path)
{
if (root==nullptr) return;
preorder(root->left, path);
path.push_back(root->val);
preorder(root->right, path);
}
void postorder(TreeNode* root, vector<int>&path)
{
if (root==nullptr) return;
preorder(root->left, path);
preorder(root->right, path);
path.push_back(root->val);
}

非递归方法

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
void preorder(TreeNode* root, vector<int>&path)
{
stack<pair(TreeNode*, bool)> s;
// initiate stack
s.push(make_pair(root, false));

bool visited = false;
TreeNode* p = root;
while(!s.empty())
{
p = s.top.first;
visited = s.top.second;

s.pop();
if (p==nullptr) continue;

if (visited)
{
path.push_back(p->val);
}
else
{
s.push(make_pair(p->right, false));
s.push(make_pair(p->left, false));
s.push(make_pair(p, true));
}
}
}

void inorder(TreeNode* root, vector<int>&path)
{
stack<pair(TreeNode*, bool)> s;
// initiate stack
s.push(make_pair(root, false));

bool visited = false;
TreeNode* p = root;
while(!s.empty())
{
p = s.top.first;
visited = s.top.second;

s.pop();
if (p==nullptr) continue;

if (visited)
{
path.push_back(p->val);
}
else
{
s.push(make_pair(p->right, false));
s.push(make_pair(p, true));
s.push(make_pair(p->left, false));
}
}
}

void postorder(TreeNode* root, vector<int>&path)
{
stack<pair(TreeNode*, bool)> s;
// initiate stack
s.push(make_pair(root, false));

bool visited = false;
TreeNode* p = root;
while(!s.empty())
{
p = s.top.first;
visited = s.top.second;

s.pop();
if (p==nullptr) continue;

if (visited)
{
path.push_back(p->val);
}
else
{
s.push(make_pair(p, true));
s.push(make_pair(p->right, false));
s.push(make_pair(p->left, false));
}
}
}

Reference: https://blog.csdn.net/czy47/article/details/81254984