Skip to the code
cf.
+25 XP

#330 Postorder Build Steps

medium

A bundler describes how to build an app as a binary tree of targets. A target can only be built after both of its sub-targets (left and right) are built. The bundler always builds the whole left side before the right side.

Write buildSteps(root) that returns the target ids in the order they get built: postorder, meaning the left subtree, then the right subtree, then the node. Don't use recursion, because the tree can be very deep. An empty tree returns [].

Example 1

Input: root = [1,2,3,4,5]
Output: [4,5,2,3,1]

2 needs 4 and 5 first, and the root 1 comes last.

Example 2

Input: root = [1,null,2,3]
Output: [3,2,1]

3 must be built before 2, and 2 before 1.

Constraints

  • 0 <= number of targets <= 100000

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).