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.
This hint is reminiscent of the use of stacks or recursion to do. However, in the strict sense this is done using extra space. Discuss has a good non-recursive algorithm, which seems to be the application of Morris traversal:
Records a node cur, starting at the root node. For this cur node, if there is a left dial hand tree, do two things:
1. Point to the right of the right-hand node of the left subtree to the cur.
2. The right pointer of cur points to the left subtree of cur, and cur to null.
If there is no left subtree, do not do these two things.
This flattens a node. Then move the cur to Cur's right child root node (the original Zogen node), and then continue repeating the two things until cur is null.
The code is as follows:
1 Public voidFlatten (TreeNode root) {2TreeNode cur =Root;3 while(cur!=NULL) {4 if(cur.left!=NULL) {5TreeNode leftright =Cur.left;6 while(leftright.right!=NULL)7LeftRight =Leftright.right;8Leftright.right =Cur.right;9Cur.right =Cur.left;TenCur.left =NULL; One } ACur =Cur.right; - } -}
Attached: A pre-order traversal approach using the stack implementation:
1 Public voidFlatten (TreeNode root) {2Stack<treenode> st =NewStack<treenode>();3 St.push (root);4 if(root==NULL)5 return;6 while(!st.isempty ())7 {8TreeNode temp =St.pop ();9 if(temp.right!=NULL)Ten St.push (temp.right); One if(temp.left!=NULL) A St.push (temp.left); -temp.left=NULL; - if(!st.isempty ()) theTemp.right =St.peek (); - Else -Temp.right =NULL; - } +}
[Leetcode] [JAVA] Flatten Binary Tree to Linked List