Algo-Sim › Binary Trees & BST

Flatten Binary Tree to Linked List

Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Rewire the tree in place into a right-pointing list in preorder: splice each left subtree between a node and its right subtree, using O(1) extra space.

Problem

Flatten a binary tree in place into a "linked list" that uses the same nodes: each node’s right points to the next node in preorder and every left is null.

Constraints

Edge cases to test

Follow-up questions

Can you avoid recursion?
Morris-style: for each node with a left child, find the rightmost node of the left subtree, hook the right subtree there, and move left to right: O(n), O(1).
What is the reverse-preorder trick?
Visit right, left, node and set node.right = prev, node.left = null: one short recursion.

Solution

Java

public void flatten(TreeNode root) {
    TreeNode node = root;
    while (node != null) {
        if (node.left != null) {
            TreeNode tail = node.left;
            while (tail.right != null) tail = tail.right;
            tail.right = node.right;
            node.right = node.left;
            node.left = null;
        }
        node = node.right;
    }
}

Python

def flatten(root):
    node = root
    while node:
        if node.left:
            tail = node.left
            while tail.right:
                tail = tail.right
            tail.right = node.right
            node.right, node.left = node.left, None
        node = node.right

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    void flatten(TreeNode *root) {
        TreeNode *node = root;
        while (node != nullptr) {
            if (node->left != nullptr) {
                TreeNode *tail = node->left;
                while (tail->right != nullptr)
                    tail = tail->right;
                tail->right = node->right;
                node->right = node->left;
                node->left = nullptr;
            }
            node = node->right;
        }
    }
};

More Binary Trees & BST problems