-
Notifications
You must be signed in to change notification settings - Fork 0
/
114.flatten-binary-tree-to-linked-list.cpp
64 lines (64 loc) · 1.61 KB
/
114.flatten-binary-tree-to-linked-list.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
/**
* 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:
void flatten(TreeNode* root) {
// version 1 : dfs recursive
/*
if (!root) {
return;
}
flatten(root->left);
flatten(root->right);
TreeNode* tmp = root->right;
root->right = root->left;
root->left = NULL;
while (root->right) {
root = root->right;
}
root->right = tmp;
*/
// version 2 : dfs non-recursive
/*
TreeNode *cur = root;
while (cur) {
if (cur->left) {
TreeNode* p = cur->left;
while (p->right) {
p = p->right;
}
p->right = cur->right;
cur->right = cur->left;
cur->left = NULL;
}
cur = cur->right;
}
*/
// version 3 : dfs non-recursive preorder traversal
if (!root) return;
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* t = s.top(); s.pop();
if (t->left) {
TreeNode *r = t->left;
while (r->right) {
r = r->right;
}
r->right = t->right;
t->right = t->left;
t->left = NULL;
}
if (t->right) {
s.push(t->right);
}
}
}
};