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
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void flatten(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root==NULL) return; flatten2list(root); return; } TreeNode* flatten2list(TreeNode* root){ if(root->left==NULL&&root->right==NULL) { return root; } if(root->left==NULL) return flatten2list(root->right); if(root->right==NULL) { root->right=root->left; TreeNode* left=root->left; root->left=NULL; return flatten2list(left); } TreeNode* right=root->right; TreeNode* left=root->left; root->right=root->left; root->left=NULL; TreeNode* middle=flatten2list(left); middle->right=right; middle->left=NULL; return flatten2list(right); } };