-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree Inorder Traversal.cpp
73 lines (69 loc) · 1.3 KB
/
Binary Tree Inorder Traversal.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
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
/*
Recursive
void solve(TreeNode* root, vector<int> &res) {
if(!root) {
return;
}
solve(root->left, res);
res.push_back(root->val);
solve(root->right, res);
}
*/
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) {
return res;
}
stack<TreeNode *> s;
TreeNode *cur;
//s.push(root);
while(!s.empty() || root) {
if(root != NULL) {
s.push(root);
root = root->left;
}
else {
root = s.top();
s.pop();
res.push_back(root->val);
root = root->right;
}
}
return res;
}
};
TreeNode *buildTree(int depth, int &val) {
TreeNode *root = new TreeNode(val);
if(depth == 0) {
return root;
}
root->left = buildTree(depth - 1, ++val);
root->right = buildTree(depth - 1, ++val);
return root;
}
int main() {
int val = 1;
TreeNode *tree = buildTree(2, val);
Solution s;
std::vector<int> res;
res = s.inorderTraversal(tree);
for(int i = 0; i < res.size(); i++) {
cout << res[i] << endl;
}
return 0;
}