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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Problem: we can see that the tree obtained after flatten is actually the first-order traversal of the original tree, and the left child of the obtained tree has null, the right child is the next node where the original tree goes through the previous sequence.
You can use recursion to traverse the tree in order, and use lastnode to save the information of the previous node. In the recursion process, pay attention to saving the right child of the root node, this is because the right sub-pointer of the root node is re-assigned during recursive traversal of the left sub-tree, and the right sub-tree is lost.
The Code is as follows:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 public class Solution {11 private TreeNode lastNode = null;12 public void flatten(TreeNode root) {13 if(root == null)14 return;15 16 if(lastNode != null){17 lastNode.left = null;18 lastNode.right = root;19 }20 21 lastNode = root;22 23 TreeNode right = root.right;24 flatten(root.left);25 flatten(right);26 }27 }