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.
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 struct Node 11 { 12 TreeNode *head; 13 TreeNode *tail; 14 Node(){} 15 Node(TreeNode *h, TreeNode *t):head(h), tail(t){} 16 }; 17 18 class Solution { 19 public: 20 Node convert(TreeNode *root) 21 { 22 if (root == NULL) 23 return Node(NULL, NULL); 24 25 Node leftNode = convert(root->left); 26 Node rightNode = convert(root->right); 27 28 root->right = NULL; 29 root->left = NULL; 30 31 if (leftNode.head) 32 { 33 root->right = leftNode.head; 34 leftNode.tail->right = rightNode.head; 35 36 } 37 else 38 { 39 root->right = rightNode.head; 40 } 41 42 TreeNode *tail; 43 if (rightNode.tail != NULL) 44 tail = rightNode.tail; 45 else if (leftNode.tail != NULL) 46 tail = leftNode.tail; 47 else 48 tail = root; 49 50 return Node(root, tail); 51 } 52 53 void flatten(TreeNode *root) { 54 // Start typing your C/C++ solution below 55 // DO NOT write int main() function 56 convert(root); 57 } 58 };