-
Notifications
You must be signed in to change notification settings - Fork 12
/
BinaryTreeInorderTraversal.cpp
52 lines (49 loc) · 1.04 KB
/
BinaryTreeInorderTraversal.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
#include "LeetCode.h"
/**
* Recursive
*/
class Solution {
public:
vector<int> result;
void inorder(TreeNode* root) {
if (!root) return;
inorder(root->left);
result.push_back(root->val);
inorder(root->right);
}
vector<int> inorderTraversal(TreeNode *root) {
result.clear();
inorder(root);
return result;
}
};
/* Morris inorder traversal */
class Solution {
public:
TreeNode* getPre(TreeNode* root) {
TreeNode* cur = root->left;
while(cur && cur->right && cur->right != root) cur=cur->right;
return cur;
}
vector<int> inorderTraversal(TreeNode *root) {
vector<int> result;
TreeNode* cur = root;
while(cur) {
TreeNode* pre = getPre(cur);
if (!pre) {
result.push_back(cur->val);
cur = cur->right;
} else {
if (pre->right == cur) {
result.push_back(cur->val);
pre->right = NULL;
cur = cur->right;
} else {
pre->right = cur;
cur = cur->left;
}
}
}
return result;
}
};