Problem 409360 · medium · Phase 04 Non-Linear Data Structures

Teardown Order of a Component Tree

n-ary tree · postorder · stack

A user interface is an N-ary tree of components (Node objects with val and children). To shut the interface down, every component must be torn down after all of its children, and children are torn down from left to right. Return the component names in teardown order (postorder). Return [] for an empty tree.

Examples

Input:  root = Node("app", [Node("header", [Node("logo"), Node("nav")]), Node("footer")])
Output: ["logo", "nav", "header", "footer", "app"]

Input:  root = Node("only")
Output: ["only"]

Constraints

  • 0 <= number of nodes <= 10**4, depth up to 1500 (an iterative solution is safer)
  • Target: O(n) time

Goals

  • Produce a postorder sequence from an N-ary tree without recursion
  • Derive postorder by reversing a modified preorder
Starting Python…