-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflattentree.cpp
45 lines (38 loc) · 920 Bytes
/
flattentree.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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {
}
* };
*/
class Solution {
void fl(TreeNode * node, TreeNode *& head, TreeNode *& tail) {
if (node == NULL) {
head = NULL;
tail = NULL;
return;
}
TreeNode * lefthead,*lefttail,*righthead,*righttail;
fl(node->left,lefthead,lefttail);
fl(node->right,righthead,righttail);
node ->left = NULL;
node->right = lefthead;
if (lefttail == NULL) lefttail = node;
lefttail->right = righthead;
head = node;
tail = node;
if (lefttail!=NULL)
tail = lefttail;
if (righttail!=NULL)
tail = righttail;
}
public:
void flatten(TreeNode *root) {
TreeNode* head;
TreeNode* tail;
fl(root,head,tail);
}
};