Flatten Binary Tree to Linked List

Source

Given a binary tree, flatten it to a linked list in-place.

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        flatten1(root);
    }

    public TreeNode flatten1(TreeNode root){
        if(root==null) return null;
        TreeNode rtree = root.right;
        if(root.left!=null){
            root.right = root.left;
            root.left=null;
            root = flatten1(root.right);
        }
        if(rtree!=null){
            root.right=rtree;
            root=flatten1(rtree);
        }
        return root;
    }
}