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
tag: binary tree, DFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private class Chunk{
TreeNode head;
TreeNode tail;
public Chunk(TreeNode head, TreeNode tail){
this.head = head;
this.tail = tail;
}
}
public void flatten(TreeNode root) {
if (root == null) return;
helper(root);
}
private Chunk helper(TreeNode root){
if (root == null) return null;
Chunk leftChunk = helper(root.left);
Chunk rightChunk = helper(root.right);
root.left = null;
Chunk curChunk = new Chunk(root, root);
if (leftChunk != null) {
curChunk.tail.right = leftChunk.head;
curChunk.tail = leftChunk.tail;
}
if (rightChunk != null){
curChunk.tail.right = rightChunk.head;
curChunk.tail = rightChunk.tail;
}
return curChunk;
}
}
一定要注意root.left = null;