Fork me on GitHub

Flatten Binary Tree to Linked List

Description

https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/

Solution

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
/**
* 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) {
if (root == NULL) return;
this->transform(root);
}
TreeNode* transform(TreeNode* root) {
TreeNode* temp = root->right;
TreeNode* current = root;
if (root->left != NULL) {
root->right = root->left;
current = this->transform(root->left);
current->left = NULL;
root->left = NULL;
current->right = temp;
}
if (temp == NULL) return current;
current = this->transform(temp);
return current;
}
};