-
Notifications
You must be signed in to change notification settings - Fork 12
/
FlattenBinaryTreetoLinkedList.cpp
49 lines (45 loc) · 1.05 KB
/
FlattenBinaryTreetoLinkedList.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
#include "LeetCode.h"
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* flattenWithTail(TreeNode* root) {
if (root == NULL) return NULL;
if (root->right == NULL && root->left == NULL) return root;
TreeNode *lt=flattenWithTail(root->left), *rt = flattenWithTail(root->right);
if (lt) {
lt->right = root->right;
root->right = root->left;
root->left = NULL;
return rt? rt:lt;
} else {
return rt;
}
}
void flatten(TreeNode *root) {
if (root) flattenWithTail(root);
}
};
/* Solution 2 */
class Solution {
public:
void flatten(TreeNode *root) {
if (!root) return;
TreeNode* left = root->left;
TreeNode* right= root->right;
root->left = root->right = nullptr;
flatten(left);
flatten(right);
root->right = left;
TreeNode* tail = root;
while(tail->right) tail=tail->right;
tail->right = right;
}
};