Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
    1
   / \
  2   5
 / \   \
3   4   6The flattened tree should look like:
1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6class Solution {
    public TreeNode helper(TreeNode root) {
        if (root.left == null && root.right == null)
            return root;
        TreeNode lowestRight = null;
        if (root.left != null && root.right != null) {
            TreeNode leftLowest = helper(root.left);
            TreeNode rightLowest = helper(root.right);
            leftLowest.right = root.right;
            root.right = root.left;
            root.left = null;
            lowestRight = rightLowest;
        } else if (root.right != null) {
            lowestRight = helper(root.right);
        } else {
            lowestRight = helper(root.left);
            root.right = root.left;
            root.left = null;
        }
        return lowestRight;
    }
    public void flatten(TreeNode root) {
        if(root==null)
            return;
        helper(root);
    }
}Last updated