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
Just put the elephant in the refrigerator for a few steps.
1. Flatten the left subtree. 2. insert it to the right subtree of the root node and the root node. 3. Repeat 1, 2.
The idea is not difficult, and the code is a bit confusing. The implementation of the details is: Make the left subtree of the root into the flatten (root. left), save the right subtree temp = root. right, let root. right = root. left, and then the left, Root. left = NULL.
Then go to the far end of the right side, while (root. Right! = NULL) root = root. Right and then root. Right = temp to continue processing.
The Code is as follows:
public void flatten(TreeNode root) { if(root==null) return; TreeNode p=root; while(p!=null){ if(p.left==null){ p=p.right; } else { if(p.right==null) { TreeNode temp=p.left; p.left=null; p.right=temp; p=p.right; } else { TreeNode tempRight=p.right; TreeNode tempLeft=p.left; p.right=null; flatten(p.left); p.left=null; p.right=tempLeft; while(p.right!=null){ p=p.right; } p.right=tempRight; } } } }
[Leetcode] flatten binary tree to linked list