Getting everything ready for you…

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

0s

Practice › Trees

Postorder Traversal

Easy · Trees · Asked at Amazon, Microsoft, Google

Print the postorder traversal of the binary tree: left subtree, right subtree, then the node.

Input

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

Output

The node values in postorder, space-separated.

Constraints

Iteratively: produce node → right → left with one stack, then reverse it.

Example 1

Input

4
1 -1 2 3

Output

3 2 1

Example 2

Input

7
1 2 3 4 5 6 7

Output

4 5 2 6 7 3 1

Hints

  1. Postorder = left, right, node. Its reverse is node, right, left — which is preorder with the children swapped.
  2. Produce node-right-left with one stack, then reverse the result.

Approach

Run the iterative preorder but push the left child before the right one; that outputs node → right → left. Reversing that sequence gives left → right → node, i.e. postorder. One stack, no recursion.

Complexity: O(n) time · O(n) 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) {}
};

// Build a tree from level order where -1 means "no node".
Node *readTree() {
    int k;
    cin >> k;
    vector<long long> v(k);
    for (auto &x : v) cin >> x;
    if (k == 0 || v[0] == -1) return nullptr;
    Node *root = new Node(v[0]);
    queue<Node *> q;
    q.push(root);
    int i = 1;
    while (!q.empty() && i < k) {
        Node *cur = q.front();
        q.pop();
        if (i < k && v[i] != -1) q.push(cur->left = new Node(v[i]));
        i++;
        if (i < k && v[i] != -1) q.push(cur->right = new Node(v[i]));
        i++;
    }
    return root;
}

int main() {
    Node *root = readTree();
    vector<long long> out;
    stack<Node *> st;
    if (root) st.push(root);
    while (!st.empty()) {
        Node *n = st.top();
        st.pop();
        out.push_back(n->val);
        if (n->left) st.push(n->left);
        if (n->right) st.push(n->right);
    }
    reverse(out.begin(), out.end());
    for (size_t i = 0; i < out.size(); i++) cout << out[i] << (i + 1 < out.size() ? " " : "\n");
    return 0;
}

Python solution

import sys
from collections import deque

sys.setrecursionlimit(100000)

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


def build_tree(v):
    """Build a tree from level order where -1 means "no node"."""
    if not v or v[0] == -1:
        return None
    root = Node(v[0])
    q, i = deque([root]), 1
    while q and i < len(v):
        cur = q.popleft()
        if i < len(v) and v[i] != -1:
            cur.left = Node(v[i])
            q.append(cur.left)
        i += 1
        if i < len(v) and v[i] != -1:
            cur.right = Node(v[i])
            q.append(cur.right)
        i += 1
    return root


data = list(map(int, sys.stdin.read().split()))
k = data[0]
root = build_tree(data[1 : 1 + k])
rest = data[1 + k :]

out, st = [], [root] if root else []
while st:
    n = st.pop()
    out.append(n.val)
    if n.left:
        st.append(n.left)
    if n.right:
        st.append(n.right)
print(*reversed(out))

Java solution

import java.util.*;

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

    // Build a tree from level order where -1 means "no node".
    static Node readTree(Scanner sc) {
        int k = sc.nextInt();
        long[] v = new long[k];
        for (int i = 0; i < k; i++) v[i] = sc.nextLong();
        if (k == 0 || v[0] == -1) return null;
        Node root = new Node(v[0]);
        ArrayDeque<Node> q = new ArrayDeque<>();
        q.add(root);
        int i = 1;
        while (!q.isEmpty() && i < k) {
            Node cur = q.poll();
            if (i < k && v[i] != -1) q.add(cur.left = new Node(v[i]));
            i++;
            if (i < k && v[i] != -1) q.add(cur.right = new Node(v[i]));
            i++;
        }
        return root;
    }

    public static void main(String[] args) {
        Node root = readTree(new Scanner(System.in));
        List<Long> out = new ArrayList<>();
        Deque<Node> st = new ArrayDeque<>();
        if (root != null) st.push(root);
        while (!st.isEmpty()) {
            Node n = st.pop();
            out.add(n.val);
            if (n.left != null) st.push(n.left);
            if (n.right != null) st.push(n.right);
        }
        Collections.reverse(out);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < out.size(); i++) sb.append(out.get(i)).append(i + 1 < out.size() ? " " : "");
        System.out.println(sb);
    }
}

Solve Postorder Traversal online · All practice problems