-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path94.cpp
More file actions
49 lines (48 loc) · 1 KB
/
94.cpp
File metadata and controls
49 lines (48 loc) · 1 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
// iteration.cpp
/**
* 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 {
vector<int> inorder;
public:
vector<int> inorderTraversal(TreeNode *root) {
stack<TreeNode *> st;
while (1) {
while (root != NULL) {
st.push(root);
root = root->left;
}
if (st.empty())
break;
root = st.top();
st.pop();
inorder.push_back(root->val);
root = root->right;
}
return inorder;
}
};
class SolutionDFS {
void impl(vector<int>& res, TreeNode* node) {
if (!node) return;
if (node->left) {
impl(res, node->left);
}
res.push_back(node->val);
if (node->right) {
impl(res, node->right);
}
}
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
impl(res, root);
return res;
}
};