Binary Tree Preorder Traversal

Given the root of a binary tree, return the preorder traversal of its nodes' values: visit a node, then its whole left subtree, then its whole right subtree.

30:00

Binary Tree Preorder Traversal
easy
Free written solution
Topics
Companies

Given the root of a binary tree, return the preorder traversal of its nodes' values: visit a node, then its whole left subtree, then its whole right subtree.

Example 1:
Input: {"root":[1,2,3,4,5,null,8,null,null,6,7,9]}
Output: [1,2,4,5,6,7,3,8,9]
Constraints:
  • The number of nodes in the tree is in the range [0,100][0, 100].

  • −100≤Node.val≤100-100 \leq \text{Node.val} \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,2,3,4,5,null,8,null,null,6,7,9]}

Push the root 1. The top of the stack is always the next node to visit.

123458679

stack

top = next visit

1

res (visit order)

[]

just popped and visited
waiting on the stack (dashed = top)
visited, badge = order
Variables
VariableValue
nodenull
stack[1]
res[]
DepthFunction Call
Stack empty
0/22