-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path二叉树的中序遍历.cpp
81 lines (65 loc) · 1.15 KB
/
二叉树的中序遍历.cpp
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
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <utility>
#include <unordered_map>
#include <functional>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root)
{
if (root == nullptr)
return {};
vector<int> res;
vector<TreeNode *> temp;
TreeNode *p = root;
while (p || !temp.empty())
{
while (p)
{
temp.push_back(p);
p = p->left;
}
p = temp.back();
temp.pop_back();
res.push_back(p->val);
p = p->right;
}
return res;
}
};
int main()
{
TreeNode node1(1);
TreeNode node2(2);
TreeNode node3(3);
TreeNode node4(4);
TreeNode node5(5);
TreeNode node6(6);
TreeNode node7(7);
TreeNode node8(8);
node1.left = &node2;
node1.right = &node3;
node2.left = &node4;
node2.right = &node5;
node3.left = &node6;
node3.right = &node7;
node4.left = &node8;
Solution a;
auto b = a.inorderTraversal(&node1);
for (auto i : b)
cout << i << " ";
cout << endl;
system("pause");
return 0;
}