Binary Tree Preorder Traversal

Easy · Trees · Stack · Tree · Depth-First Search · Binary Tree

Problem

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

The recursive version is three lines. As a follow-up, produce the same order iteratively with an explicit stack, and then with no stack at all.

Examples

Input: root = [6,2,8,1,4]
Output: [6,2,1,4,8]

Root 6 first, then the left subtree 2, 1, 4, then the right node 8.

Input: root = [3,null,5,7]
Output: [3,5,7]

3 has only a right child 5, whose left child is 7.

Input: root = []
Output: []

An empty tree has no values.

Constraints

Approaches

Follow-up

Inorder and postorder fit the same frameworks. With a stack, inorder walks left as far as possible before visiting; postorder is preorder with the children swapped (node, right, left), reversed. With Morris, inorder records on the second visit instead of the first.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…