Ctrl K

Parent Before Children

Easy
You are given the root of a binary tree. Imagine walking down the tree and writing down each node the moment you enter it. The rule: for every node, first the node itself is written, then its entire left subtree, then its entire right subtree. Return the values in the order they were written. 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([5, 2, 9, 1, 3, None, 11]) → [5, 2, 1, 3, 9, 11]

The root 5, then its whole left subtree (2, 1, 3), then the right one (9, 11).

Example 2
root=tree_node([4, None, 6, 8]) → [4, 6, 8]

4, then its right child 6, then 6's left child 8.

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

An empty tree gives an empty 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 EasyChildren Before Parent EasySearch Tree Into a Line EasyTree Into a Right Chain MediumK Keys Nearest to a Target Hard
loading Python…
Input
root=tree_node([5, 2, 9, 1, 3, None, 11])
Expected
[5, 2, 1, 3, 9, 11]

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