Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Trees

Flatten a Binary Tree to a List

Medium · Trees · Asked at Amazon, Microsoft, Meta, Adobe

Flatten the tree in place into a "linked list" that uses the right pointers: the nodes must appear in preorder (root, left subtree, right subtree), and every left pointer becomes null. Print the values of the flattened list from the root, following right pointers.

Input

First line: k. Second line: k values — the tree in level order, -1 means no node.

Output

The values along the flattened list, space-separated.

Constraints

For each node with a left child: find the rightmost node of the left subtree, attach the current right subtree there, move the left subtree to the right and clear the left pointer. Then continue with the right child. O(n) time and O(1) extra space (Morris-style).

Example 1

Input

7
1 2 5 3 4 -1 6

Output

1 2 3 4 5 6

Example 2

Input

1
7

Output

7

Hints

  1. In preorder, the whole left subtree comes right after the node, before the right subtree.
  2. So the right subtree should hang off the last node of the left subtree in preorder — its rightmost node.

Approach

Walk cur down the right pointers. Whenever cur has a left child: find the rightmost node of the left subtree, attach cur.right to it, move cur.left to cur.right, and set cur.left = null. Then continue with cur.right. Every node is visited a constant number of times overall, with O(1) extra memory. Finally print the values along the right pointers.

Complexity: O(n) time · O(1) extra space

Solution

C++ solution

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

struct Node {
    long long val;
    Node *left = nullptr, *right = nullptr;
    Node(long long v) : val(v) {}
};

// level order with -1 for a missing child
Node *build(const vector<long long> &a) {
    if (a.empty() || a[0] == -1) return nullptr;
    Node *root = new Node(a[0]);
    queue<Node *> q;
    q.push(root);
    size_t i = 1;
    while (!q.empty() && i < a.size()) {
        Node *cur = q.front();
        q.pop();
        if (i < a.size() && a[i] != -1) q.push(cur->left = new Node(a[i]));
        i++;
        if (i < a.size() && a[i] != -1) q.push(cur->right = new Node(a[i]));
        i++;
    }
    return root;
}

vector<long long> readTree() {
    int k;
    cin >> k;
    vector<long long> a(k);
    for (auto &x : a) cin >> x;
    return a;
}

int main() {
    Node *root = build(readTree());
    for (Node *cur = root; cur; cur = cur->right) {
        if (cur->left) {
            Node *pre = cur->left;
            while (pre->right) pre = pre->right;
            pre->right = cur->right;
            cur->right = cur->left;
            cur->left = nullptr;
        }
    }
    for (Node *p = root; p; p = p->right) cout << p->val << (p->right ? " " : "\n");
    return 0;
}

Python solution

import sys
from collections import deque

class Node:
    __slots__ = ("val", "left", "right")

    def __init__(self, val):
        self.val, self.left, self.right = val, None, None


def build(a):
    """Level order with -1 for a missing child."""
    if not a or a[0] == -1:
        return None
    root = Node(a[0])
    q = deque([root])
    i = 1
    while q and i < len(a):
        cur = q.popleft()
        if i < len(a) and a[i] != -1:
            cur.left = Node(a[i])
            q.append(cur.left)
        i += 1
        if i < len(a) and a[i] != -1:
            cur.right = Node(a[i])
            q.append(cur.right)
        i += 1
    return root


data = list(map(int, sys.stdin.read().split()))
root = build(data[1 : 1 + data[0]])
cur = root
while cur:
    if cur.left:
        pre = cur.left
        while pre.right:
            pre = pre.right
        pre.right = cur.right
        cur.right = cur.left
        cur.left = None
    cur = cur.right
out, p = [], root
while p:
    out.append(p.val)
    p = p.right
print(*out)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    static class Node {
        long val;
        Node left, right;
        Node(long v) { val = v; }
    }

    // level order with -1 for a missing child
    static Node build(long[] a) {
        if (a.length == 0 || a[0] == -1) return null;
        Node root = new Node(a[0]);
        ArrayDeque<Node> q = new ArrayDeque<>();
        q.add(root);
        int i = 1;
        while (!q.isEmpty() && i < a.length) {
            Node cur = q.poll();
            if (i < a.length && a[i] != -1) q.add(cur.left = new Node(a[i]));
            i++;
            if (i < a.length && a[i] != -1) q.add(cur.right = new Node(a[i]));
            i++;
        }
        return root;
    }

    static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

    static long next() throws IOException {
        in.nextToken();
        return (long) in.nval;
    }

    static long[] readTree() throws IOException {
        int k = (int) next();
        long[] a = new long[k];
        for (int i = 0; i < k; i++) a[i] = next();
        return a;
    }

    public static void main(String[] args) throws IOException {
        Node root = build(readTree());
        for (Node cur = root; cur != null; cur = cur.right) {
            if (cur.left != null) {
                Node pre = cur.left;
                while (pre.right != null) pre = pre.right;
                pre.right = cur.right;
                cur.right = cur.left;
                cur.left = null;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Node p = root; p != null; p = p.right) sb.append(p.val).append(p.right != null ? " " : "\n");
        System.out.print(sb);
    }
}

Solve Flatten a Binary Tree to a List online · All practice problems