LeetCode

Flatten Binary Tree to Linked List

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

Java

public class Solution {
    public void flatten(TreeNode root) {
        helper(root);
    }

    public TreeNode helper(TreeNode root) {
        if(root == null) {
            return null;
        } 
        TreeNode left = root.left;
        TreeNode right = root.right;
        root.left = null;
        root.right = null;

        if(left != null) {
            root.right = left;
            root = helper(left);
        }
        if(right != null) {
            root.right = right;
            root = helper(right);
        }
        return root;
    }
}