Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void DFS(TreeNode* root, vector<int>& nums){
if(!root) return;
nums.push_back(root->val);
DFS(root->left, nums);
DFS(root->right, nums);
}
void flatten(TreeNode* root) {
if(!root) return;
vector<int> nums;
DFS(root, nums);
root->val = nums[0];
root->left = NULL;
TreeNode* pre = root;
for(int i = 1; i < nums.size(); ++i){
TreeNode* temp = new TreeNode(nums[i]);
pre->right = temp;
pre = temp;
}
}