cswork / templatesOpen the Line 500 list

STOP 12 · LISTS & TREES

Binary Tree Construction and Transformation

Preorder picks the root, inorder splits the sides O(n) time · O(n) space

Contest ratings Rating 1511–Rating 1511· median Rating 1511(1 of 6 problems rated by zerotrac)

Open the Line 500 list · stop 12 · 6 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 3 companies · in 4 reportsNVIDIA 2, StackAdapt 1, TikTok / ByteDance 1

Warm up with this one

LC 105Construct Binary Tree from Preorder and Inorder TraversalMedium
Stuck? Peek at the approach

Use preorder to identify the root and inorder to split subtrees while maintaining index bounds.

Key points

  1. The first preorder value is the root; find it in inorder, and everything to its left is the left subtree, everything to its right the right subtree.
  2. A value-to-inorder-index map makes each split O(1) and the whole build O(n).
  3. Recursing left before right, the next preorder value is always the next root, so no lengths are needed; with postorder plus inorder, read from the back and build right before left.

Common pitfalls

  • With duplicate values the inorder position is ambiguous and this method breaks.
  • Copying subarrays at every level (Python slices, Java copyOfRange) degrades the build to O(n²).
  • With postorder plus inorder, building the left subtree first takes the roots in the wrong order.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Tree traversal · stack and queue

Walk the tree in preorder, inorder, postorder, level order

Try your own input
ABCDEFG
CurrentDiscovered / computedAnswer
Stack bottom → top, or queue front → back
Empty
Order
Preorder
Output
—

One tree, four traversal orders. #k under a node is its position in the current output.

InvariantThe three depth-first orders differ only in where the root is output: before, between or after its subtrees. Level order uses a queue, and first in, first out means level by level.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 105, with it.

Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def build_tree(preorder: list[int], inorder: list[int]):
    """Rebuild a tree with distinct values from its preorder and inorder walks."""
    pos = {v: i for i, v in enumerate(inorder)}  # value -> inorder index: O(1) splits
    roots = iter(preorder)  # preorder yields roots in exactly the order we build them

    def build(lo: int, hi: int):  # the subtree whose inorder range is [lo, hi)
        if lo == hi:
            return None
        root = TreeNode(next(roots))
        mid = pos[root.val]
        root.left = build(lo, mid)  # left before right, matching preorder
        root.right = build(mid + 1, hi)
        return root

    return build(0, len(inorder))
C++
struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};

// Rebuild a tree with distinct values from its preorder and inorder walks.
TreeNode* buildTree(const vector<int>& preorder, const vector<int>& inorder) {
    unordered_map<int, int> pos;  // value -> inorder index: O(1) splits
    for (int i = 0; i < (int)inorder.size(); i++) pos[inorder[i]] = i;
    int next = 0;  // preorder yields roots in exactly the order we build them
    function<TreeNode*(int, int)> build = [&](int lo, int hi) -> TreeNode* {  // inorder [lo, hi)
        if (lo == hi) return nullptr;
        TreeNode* root = new TreeNode(preorder[next++]);
        int mid = pos[root->val];
        root->left = build(lo, mid);  // left before right, matching preorder
        root->right = build(mid + 1, hi);
        return root;
    };
    return build(0, inorder.size());
}
Java
class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    private int[] preorder;
    private int next; // preorder yields roots in exactly the order we build them
    private final Map<Integer, Integer> pos = new HashMap<>(); // value -> inorder index

    // Rebuild a tree with distinct values from its preorder and inorder walks.
    TreeNode buildTree(int[] preorder, int[] inorder) {
        this.preorder = preorder;
        next = 0;
        pos.clear();
        for (int i = 0; i < inorder.length; i++) pos.put(inorder[i], i);
        return build(0, inorder.length);
    }

    private TreeNode build(int lo, int hi) { // the subtree whose inorder range is [lo, hi)
        if (lo == hi) return null;
        TreeNode root = new TreeNode(preorder[next++]);
        int mid = pos.get(root.val);
        root.left = build(lo, mid); // left before right, matching preorder
        root.right = build(mid + 1, hi);
        return root;
    }
}
Go
type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// buildTree rebuilds a tree with distinct values from its preorder and inorder walks.
func buildTree(preorder, inorder []int) *TreeNode {
	pos := make(map[int]int, len(inorder)) // value -> inorder index: O(1) splits
	for i, v := range inorder {
		pos[v] = i
	}
	next := 0                            // preorder yields roots in exactly the order we build them
	var build func(lo, hi int) *TreeNode // the subtree whose inorder range is [lo, hi)
	build = func(lo, hi int) *TreeNode {
		if lo == hi {
			return nil
		}
		root := &TreeNode{Val: preorder[next]}
		next++
		mid := pos[root.Val]
		root.Left = build(lo, mid) // left before right, matching preorder
		root.Right = build(mid+1, hi)
		return root
	}
	return build(0, len(inorder))
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Inorder + postorder: read postorder backwardsO(n) time · O(n) space

Given inorder and postorder (LC 106): postorder read backwards is root, right, left, so after taking each root build the right subtree before the left. The root's inorder position still comes from a hash map in O(1) and splits the range in two.

Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def build_from_post(inorder: list[int], postorder: list[int]):
    """Rebuild a tree with distinct values from its inorder and postorder walks (LC 106)."""
    pos = {v: i for i, v in enumerate(inorder)}  # value -> inorder index
    roots = reversed(postorder)  # backwards, postorder yields root, then right, then left

    def build(lo: int, hi: int):  # the subtree whose inorder range is [lo, hi)
        if lo == hi:
            return None
        root = TreeNode(next(roots))
        mid = pos[root.val]
        root.right = build(mid + 1, hi)  # right first, matching the reversed postorder
        root.left = build(lo, mid)
        return root

    return build(0, len(inorder))
C++
struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};

// Rebuild a tree with distinct values from its inorder and postorder walks (LC 106).
TreeNode* buildFromPost(const vector<int>& inorder, const vector<int>& postorder) {
    unordered_map<int, int> pos;  // value -> inorder index
    for (int i = 0; i < (int)inorder.size(); i++) pos[inorder[i]] = i;
    int next = (int)postorder.size() - 1;  // backwards, postorder yields root, then right, then left
    function<TreeNode*(int, int)> build = [&](int lo, int hi) -> TreeNode* {  // inorder range [lo, hi)
        if (lo == hi) return nullptr;
        TreeNode* root = new TreeNode(postorder[next--]);
        int mid = pos[root->val];
        root->right = build(mid + 1, hi);  // right first, matching the reversed postorder
        root->left = build(lo, mid);
        return root;
    };
    return build(0, inorder.size());
}
Java
class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    private final Map<Integer, Integer> pos = new HashMap<>(); // value -> inorder index
    private int[] postorder;
    private int next;

    // Rebuild a tree with distinct values from its inorder and postorder walks (LC 106).
    TreeNode buildFromPost(int[] inorder, int[] postorder) {
        pos.clear();
        for (int i = 0; i < inorder.length; i++) pos.put(inorder[i], i);
        this.postorder = postorder;
        next = postorder.length - 1; // backwards, postorder yields root, then right, then left
        return build(0, inorder.length);
    }

    // The subtree whose inorder range is [lo, hi).
    private TreeNode build(int lo, int hi) {
        if (lo == hi) return null;
        TreeNode root = new TreeNode(postorder[next--]);
        int mid = pos.get(root.val);
        root.right = build(mid + 1, hi); // right first, matching the reversed postorder
        root.left = build(lo, mid);
        return root;
    }
}
Go
type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// buildFromPost rebuilds a tree with distinct values from its inorder and postorder walks (LC 106).
func buildFromPost(inorder, postorder []int) *TreeNode {
	pos := map[int]int{} // value -> inorder index
	for i, v := range inorder {
		pos[v] = i
	}
	next := len(postorder) - 1 // backwards, postorder yields root, then right, then left
	var build func(lo, hi int) *TreeNode // the subtree whose inorder range is [lo, hi)
	build = func(lo, hi int) *TreeNode {
		if lo == hi {
			return nil
		}
		root := &TreeNode{Val: postorder[next]}
		next--
		mid := pos[root.Val]
		root.Right = build(mid+1, hi) // right first, matching the reversed postorder
		root.Left = build(lo, mid)
		return root
	}
	return build(0, len(inorder))
}
Monotonic stack builds a maximum tree in one passO(n) time · O(n) space

For trees whose every subtree root is the maximum of its range (LC 654, Maximum Binary Tree, a Cartesian tree): recursing to find each maximum is O(n²), while a stack with decreasing values takes O(n). Each new node pops the smaller nodes as its left subtree and hangs itself to the right of the larger node left on top.

Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def max_tree(nums: list[int]):
    """Maximum binary tree of distinct nums (LC 654), built in O(n)."""
    stack = []  # the right spine of the tree so far, values decreasing
    for x in nums:
        node = TreeNode(x)
        while stack and stack[-1].val < x:
            node.left = stack.pop()  # smaller nodes before x end up in its left subtree
        if stack:
            stack[-1].right = node  # x hangs right of the nearest larger value before it
        stack.append(node)
    return stack[0] if stack else None
C++
struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};

// Maximum binary tree of distinct nums (LC 654), built in O(n).
TreeNode* maxTree(const vector<int>& nums) {
    vector<TreeNode*> stack;  // the right spine of the tree so far, values decreasing
    for (int x : nums) {
        TreeNode* node = new TreeNode(x);
        while (!stack.empty() && stack.back()->val < x) {
            node->left = stack.back();  // smaller nodes before x end up in its left subtree
            stack.pop_back();
        }
        if (!stack.empty()) stack.back()->right = node;  // x hangs right of the nearest larger value
        stack.push_back(node);
    }
    return stack.empty() ? nullptr : stack[0];
}
Java
class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    // Maximum binary tree of distinct nums (LC 654), built in O(n).
    TreeNode maxTree(int[] nums) {
        Deque<TreeNode> stack = new ArrayDeque<>(); // the right spine of the tree so far, values decreasing
        for (int x : nums) {
            TreeNode node = new TreeNode(x);
            while (!stack.isEmpty() && stack.peek().val < x)
                node.left = stack.pop(); // smaller nodes before x end up in its left subtree
            if (!stack.isEmpty()) stack.peek().right = node; // x hangs right of the nearest larger value
            stack.push(node);
        }
        return stack.isEmpty() ? null : stack.peekLast();
    }
}
Go
type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// maxTree builds the maximum binary tree of distinct nums (LC 654) in O(n).
func maxTree(nums []int) *TreeNode {
	var stack []*TreeNode // the right spine of the tree so far, values decreasing
	for _, x := range nums {
		node := &TreeNode{Val: x}
		for len(stack) > 0 && stack[len(stack)-1].Val < x {
			node.Left = stack[len(stack)-1] // smaller nodes before x end up in its left subtree
			stack = stack[:len(stack)-1]
		}
		if len(stack) > 0 {
			stack[len(stack)-1].Right = node // x hangs right of the nearest larger value
		}
		stack = append(stack, node)
	}
	if len(stack) == 0 {
		return nil
	}
	return stack[0]
}

Why it works

  1. The first preorder value is always the root. With distinct values its inorder position is unique, everything left of it is exactly the left subtree and everything right of it the right subtree, so the subtree sizes are fixed and the recursion rebuilds a unique tree.
  2. Preorder is root, then the whole left subtree, then the whole right subtree, so if you recurse left before right, a single pointer reading preorder in order always lands on the next subtree's root.
  3. With duplicate values the root's inorder position is ambiguous and the tree may not be unique, which is why these problems promise distinct values.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
先序的第一个值是根,我在中序里找到它,左边是左子树、右边是右子树,然后递归构造。为了 O(1) 定位,先建一个值到中序下标的哈希表。因为先序是根、左子树、右子树的顺序,只要先建左再建右,用一个指针顺序读先序就总能拿到下一个根。整体 O(n),前提是值互不相同。
English
The first preorder value is the root; I find it in the inorder array, where everything to its left is the left subtree and everything to its right is the right subtree, and recurse. A map from value to inorder index makes each lookup O(1). Because preorder lists root, left subtree, right subtree, building left before right lets one pointer read preorder in order and always get the next root. The build is O(n), given distinct values.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

3 questions
  1. With distinct values, which traversal pairs determine a binary tree uniquely? Select all that apply.
  2. Rebuilding a tree from preorder and inorder, what does a hash map from value to inorder index change?
  3. Building a height-balanced BST from n distinct sorted values (recursing on index ranges, no slicing): which element of each range becomes the root, and what is the total time?

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

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


    return build(0, len(inorder))

Practice by stage

This stop's 6 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Core 5

#ProblemApproachRating
105Construct Binary Tree from Preorder and Inorder TraversalUse preorder to identify the root and inorder to split subtrees while maintaining index bounds.
106Construct Binary Tree from Inorder and Postorder TraversalReconstruct a tree from postorder and inorder using interval recursion adapted to the traversal order.
654Maximum Binary TreeConstruct recursively around maximum values and recognize the monotonic-stack optimization for linear construction.
114Flatten Binary Tree to Linked ListFlatten the tree in place into a preorder list, joining the left subtree's tail to the original right subtree.
1110Delete Nodes And Return ForestDelete nodes and return a forest, distinguishing retaining the current node from promoting its children to roots.Rating 1511

Advanced 1

#ProblemApproachRating
652Find Duplicate SubtreesAssign comparable identifiers to subtree structures to detect duplicate subtrees rather than repeated node values.

OA questions on this topic 1

All 1