题目如下:
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
解答如下:
思路是这样的,先把左子树调成linked_list,再把右子树调成linked_list,然后把左子树插在root的右根上,原右子树往下移。这样递归地去求解。
代码:
class Solution {
public void flatten(TreeNode root) {
if (root==null) return;
if (root.left!=null) flatten(root.left);
if (root.right!=null) flatten(root.right);
TreeNode tmp = root.right;
root.right = root.left;
root.left = null;
while (root.right!=null) root = root.right;
root.right = tmp;
}
}