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 method I: Stack
structTreeNode {intVal; TreeNode*Left ; TreeNode*Right ; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: voidFlatten (TreeNode *root) { if(!root)return; TreeNode* Flatroot =NewTreeNode (root->val); TreeNode* Flatnode =Flatroot; TreeNode*Current ; Stack<TreeNode*>Tree_stack; //stack is first into the back, so the reverse order into the stack, that is, first right son, then left son if(root->Right ) {Tree_stack.push (Root-Right ); } if(root->Left ) {Tree_stack.push (Root-Left ); } while(!Tree_stack.empty ()) { Current=Tree_stack.top (); Tree_stack.pop (); Flatnode->right =NewTreeNode (current->val); Flatnode= flatnode->Right ; //Treat the stack element as the root node and put its right son and left son on the stack again if(current->Right ) {Tree_stack.push ( current-Right ); } if(current->Left ) {Tree_stack.push ( current-Left ); } } *root = *Flatroot; }};
Method II: Recursion, pre-sequence traversal
classSolution { Public: voidFlatten (TreeNode *root) { if(!root)return; TreeNode* Newroot =NewTreeNode (root->val); Preordertraverse (Root, Newroot); *root = *Newroot; } TreeNode* Preordertraverse (TreeNode *root, TreeNode *newroot) { if(root->Left ) {Newroot->right =NewTreeNode (root->left->val); Newroot= Preordertraverse (Root->left, newroot->Right ); } if(root->Right ) {Newroot->right =NewTreeNode (root->right->val); Newroot= Preordertraverse (Root->right, newroot->Right ); } returnNewroot; }};
Flatten Binary Tree to Linked List (Stack, tree; DFS)