Problem
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 |
|
The flattened tree should look like:
1 |
|
Explanation 1
- The brute force solution is using pre-order traversal to store all elements to a list, then traversal the list’s elements and make each one’s left node to be null and right node to be its next node.
Solution 1
1 |
|
Explanation 2
-
We usually can use recursion for tree problem. For example, if we already flattern the left subtree and the right subtree, which is illustrated below:
1
2
3
4
5
6
71 / \ 2 5 \ \ 3 6 <- rightTail \ 4 <- leftTail
-
Now, how do we make
root
,root.left
, androot.right
to be a flattern list?1
2
3leftTail.right = root.right; root.right = root.left; root.left = null;
-
From the above illustration and code, we have used the already flattern list’s
leftTail
andrightTail
. Therefore, the recursion’s base case is the flattern list’s tail node.
Solution 2
1 |
|