Ctrl K

Children Before Parent

Easy
You are given the root of a binary tree. Imagine taking the tree apart: a node can be removed only after all of its descendants are gone. List the node values in removal order, following this rule: for every node, first its entire left subtree, then its entire right subtree, and only then the node itself. Return the list of values. For an empty tree, return an empty list. *The recursive version takes a couple of lines, so try doing it without recursion.*
Example 1
root=tree_node([10, 4, 8, 2, 6]) → [2, 6, 4, 8, 10]

Node 4 has children 2 and 6, so they come before it. Then 8 (no children), and the root 10 comes last.

Example 2
root=tree_node([3, None, 5, 1]) → [1, 5, 3]

The root 3 is last, 5 is right before it, and 5's child 1 comes even earlier.

Example 3
root=tree_node([-7]) → [-7]

A single node gives a one-item list.

Constraints
  • 0 ≤ number of nodes ≤ 1000
  • -1000 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLeft, Node, Right EasyParent Before Children EasySearch Tree Into a Line EasyTree Into a Right Chain MediumK Keys Nearest to a Target Hard
loading Python…
Input
root=tree_node([10, 4, 8, 2, 6])
Expected
[2, 6, 4, 8, 10]

Run checks the first 3 tests in your browser. Submit checks all 94 tests on the server, hidden ones included.