Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/
2 5
/
3 4 6
The flattened tree should look like:
1
2
3
4
5
6
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node
of a pre-order traversal.
Solution: Recursion. Return the last element of the flattened sub-tree.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void flatten(TreeNode *root) { 13 TreeNode* end = NULL; 14 flattenRe(root, end); 15 } 16 17 void flattenRe(TreeNode* root, TreeNode* &end) 18 { 19 if(!root) return; 20 TreeNode* lend = NULL; 21 TreeNode* rend = NULL; 22 flattenRe(root->left, lend); 23 flattenRe(root->right, rend); 24 if(root->left) { 25 lend->right = root->right; 26 root->right = root->left; 27 root->left = NULL; 28 } 29 end = rend ? rend : (lend ? lend : root); 30 } 31 };