-
Notifications
You must be signed in to change notification settings - Fork 4
/
Solution.cpp
47 lines (43 loc) · 1.09 KB
/
Solution.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
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <tuple>
#include <deque>
#include <unordered_map>
#include <cmath>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
// Morris Traversal, do not need extra space
// https://stackoverflow.com/questions/5502916/explain-morris-inorder-tree-traversal-without-using-stacks-or-recursion
// just reorder the tree in the output order
vector<int> inorderTraversal(TreeNode* p) {
vector<int>res;
while (p != NULL) {
if (p->left != NULL) {
auto lr = p->left, newp = p->left;
while (lr->right != NULL) lr = lr->right;
lr->right = p;
p->left = NULL;
p = newp;
} else {
res.push_back(p->val);
p = p->right;
}
}
return res;
}
};
int main() {
Solution s;
return 0;
}