題目:
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
二叉樹轉換爲右節點串聯起來的鏈表。對於每個節點,左節點是已經轉換完成的鏈表,只需要把左邊的鏈表插入到右邊節點之前就可以了。
AC:
public void flatten(TreeNode root) {
if (root == null) {
return;
}
flatten(root.left);
flatten(root.right);
if (root.left != null) {
TreeNode rightHead = root.right;
root.right = root.left;
TreeNode tmp = root.right;
while (tmp.right != null) {
tmp = tmp.right;
}
tmp.right = rightHead;
root.left = null;
}
}