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

Thoughts

Go down through the left, when right is not null, push right to stack.

Java Solution

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode p = root;
 
        while(p != null || !stack.empty()){
 
            if(p.right != null){
                stack.push(p.right);
            }
 
            if(p.left != null){
                p.right = p.left;
                p.left = null;
            }else if(!stack.empty()){
                TreeNode temp = stack.pop();
                p.right=temp;
            }
 
            p = p.right;
        }
    }
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Kartrace on 2014-3-8

    is this in place? you are using a stack…, but the solution is indeed nice!

  2. Diego Cedrim on 2014-11-16

    I wrote a code that not uses any other data structure, but uses recursion.

    The basic idea is:

    1) Find a node N with a left child L;
    2) Find the rightmost descendant of L and call it RM;
    3) Aux = N.right;
    4) N.right = L
    5) RM.right = Aux
    6) Explore the right subtree of N recursively.

    The code can be seen in http://pastebin.com/AXsgEJs7

  3. rampartmovie on 2015-1-3

    Just do an inorder traversal and then add the left node to the list. and when the node pops out and u assign right node, assign next to list again.

  4. rampartmovie on 2015-1-3

    Just do an inorder traversal and then add the left node to the list. and when the node pops out and u assign right node, assign next to list again.

  5. Lambda Pool on 2015-1-21

    very incomplete code, it doesn’t run without those accessory classes.

  6. hdante on 2015-1-22

    There’s a non recursive solution that does not use a container, only an auxiliary variable. The idea is to move the right subtree to the left subtree to free the root’s right node, then move the resulting left subtree to the right side.

  7. Noobaka on 2015-3-1

    Hi,
    I am a tad-bit confused. Isn’t this question very similar to Inorder traversal of a Binary Tree?Will it work if I just did Inorder traversal and stored all that value while doing that? Am I wrong? Please correct me.

  8. Noobaka on 2015-3-1

    I mean PreOrder Traversal.

  9. RoroZoro on 2015-4-2

    Had the same doubt. But since the problem is to “flatten” which means, we need to change the links pointed by the node, we need to do like this. But yeah, preorder gives the same answer.

  10. Almas Daumov on 2016-4-17

    @diegocedrim:disqus your code is good, but missing 1 thing – setting “node.left = nil;” before calling recursion. See http://pastebin.com/ubpZaXqf

  11. Ashish Pai on 2016-7-2

    Using recursion is not in-place right? You are using the system stack.

  12. Matias SM on 2016-8-7

    Recursive solution. Time complexity O(N), Space complexity O(H) (H: height of the tree)


    public class BinTreeNode {
    public final T value;
    public BinTreeNode left;
    public BinTreeNode right;
    }

    void flatten(BinTreeNode root) {
    flatten(root, null);
    }

    BinTreeNode flatten(BinTreeNode node, BinTreeNode last) {
    if (node == null) return last;
    BinTreeNode oldLeft = node.left;
    BinTreeNode oldRight = node.right;
    node.left = last;
    if (last != null) {
    last.right = node;
    }
    last = node;
    last = flatten(oldLeft, last);
    last = flatten(oldRight, last);
    return last;
    }

  13. Bharath Chandra on 2016-10-11


    void flatten(struct TreeNode* root) {
    struct TreeNode *temp = NULL;
    if(!root)return;
    if(root-> left){
    flatten(root-> left);
    if(root-> right){
    flatten(root-> right);
    }
    temp = root-> left;
    while(temp-> right){
    temp = temp-> right;
    }
    temp-> right = root-> right;
    root-> right = root-> left;
    root-> left = NULL;
    }
    else{
    flatten(root-> right);
    }

    }

  14. Donte on 2016-10-29

    Is this right?

  15. Bharath Chandra on 2016-10-31

    Yes, acccepted.

  16. maninblack2013 on 2017-4-29

    if p==null, p.right blows up

Leave a comment

*