Flatten Binary Tree to Linked List
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
Ideas:
There are two methods for the deformation of the first order traversal. One from the top down, one from the bottom up.
First say from the top down. From the root node, move the current node's sitting node to the right node, and the original right node is connected to the right-most node now. This way, the left side of the current node is null, and its right-hand node is the first-order traversal of the value that should be accessed next.
Say from bottom to top. For a node to operate, first assume that the right is all ordered (so first recursive right node), the rest of the same as from the top, but this method first recursion to the right node in the tree, and then start the operation.
Exercises
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: voidFlatten (TreeNode *root) { if(root==NULL)return; if(root->Left ) {TreeNode*tmp = root->Right ; Root->right = root->Left ; Root->left =NULL; TreeNode*lastright =Root; while(root->Right ) Root= root->Right ; Root->right =tmp; Root=Lastright; } Flatten (Root-Right ); }};
from the top down
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: voidFlatten (TreeNode *root) { if(root==NULL)return; if(Root->left==null && root->right==NULL)return; Flatten (Root-Right ); Flatten (Root-Left ); TreeNode*tmp = root->Right ; if(root->Left ) {Root->right = root->Left ; Root->left =NULL; while(root->Right ) Root= root->Right ; Root->right =tmp; } }};
from bottom to top
[Leetcode] Flatten Binary Tree to Linked List