-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathflatten-binary-tree-to-linked-list_2(AC).cpp
More file actions
57 lines (53 loc) · 1.22 KB
/
flatten-binary-tree-to-linked-list_2(AC).cpp
File metadata and controls
57 lines (53 loc) · 1.22 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
50
51
52
53
54
55
56
57
// Recursive solution
#include <algorithm>
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 {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void flatten(TreeNode *root) {
if (root == NULL) {
return;
}
TreeNode *left, *right;
preorder(root, left, right);
}
private:
void preorder(TreeNode *root, TreeNode *&left, TreeNode *&right) {
left = right = root;
TreeNode *ll, *lr, *rl, *rr;
if (root->left != NULL) {
preorder(root->left, ll, lr);
} else {
ll = lr = NULL;
}
if (root->right != NULL) {
preorder(root->right, rl, rr);
} else {
rl = rr = NULL;
}
left->left = NULL;
if (ll != NULL) {
right->right = ll;
right = lr;
}
if (rl != NULL) {
right->right = rl;
right = rr;
}
}
};