Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / 2 5 / \ 3 4 6
The flattened tree shoshould look like:
1 2 3 4 5 6
Algorithm: This question uses recursion. If you consider the current node, the idea is as follows: set the current node as root, point the right subtree of the rightmost node of the Left node of the root to the right subtree of the root, and then point the right pointer of the root to the left subtree, the next node processes root-> right. The Code is as follows:
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 if(NULL==root) return;14 if(NULL!=root->left)15 {16 getLeftRight(root)->right=root->right;17 root->right=root->left;18 root->left=NULL;19 }20 flatten(root->right);21 22 }23 24 TreeNode* getLeftRight(TreeNode* root)25 {26 root=root->left;27 while(NULL!=root->right) root=root->right;28 return root;29 }30 };
Flatten binary tree to linked list <leetcode>