8.7 114 Flatten Binary Tree to Linked List
Question:
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
Method: put root.left to its right, and connect root.right to its original left.right(if root.left.right == null then connect root.right to root.left)
public void flatten(TreeNode root) {
while(root != null) {
if(root.left != null) {
TreeNode lr = root.left.right;
while(lr != null && lr.right != null)
lr = lr.right;
if(lr == null) // if left has no right nodes then use root.left to connect root.right.
lr = root.left;
TreeNode temp = root.right;
root.right = root.left;
lr.right = temp;
root.left = null;
}
root = root.right;
}
}

浙公网安备 33010602011771号