-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBinary_Tree_Inorder_Traversal.cpp
108 lines (97 loc) · 2.28 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
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
/*
Given a binary tree, return the inorder traversal of its nodes' values.
Example
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
Challenge Expand
Can you do it without recursion?
*/
// version 1, recursion
#include <vector>
#include "lintcode.h"
using namespace std;
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
vector<int> inorderTraversal(TreeNode* root) {
// write your code here
vector<int> result;
inorderTraversalRecursion(root, result);
return result;
}
void inorderTraversalRecursion(TreeNode* root, vector<int>& result) {
if (!root) {
return;
}
inorderTraversalRecursion(root->left, result);
result.push_back(root->val);
inorderTraversalRecursion(root->right, result);
}
};
// version 2, iterator
#include <vector>
#include <stack>
#include "lintcode.h"
using namespace std;
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
vector<int> inorderTraversal(TreeNode* root) {
// write your code here
vector<int> result;
stack<TreeNode*> myStack;
bool done = false;
TreeNode* current = root;
while (!done) {
if (current) {
myStack.push(current);
current = current->left;
} else {
if (myStack.empty()) {
done = true;
} else {
current = myStack.top();
myStack.pop();
result.push_back(current->val);
current = current->right;
}
}
}
return result;
}
};