EasyStackTreeDepth-First SearchBinary Tree

Binary Tree Preorder Traversal

LeetCode
1 approach, code in all languages

You are given the root of a binary tree. Return the values of its nodes visited in preorder sequence.

A preorder traversal records the current node first, then traverses the entire left subtree, and finally the entire right subtree. Because the node comes before its descendants, the root always appears first and each subtree's root leads its own block of values.

This root-first ordering is commonly used to serialize a tree or to clone its structure top-down.

Example 1

Input: root = [1,null,2,3]

Output: [1,2,3]

Visit root 1, then its right child 2 (no left child), then 2's left child 3.

Example 2

Input: root = [1,2,3,4,5]

Output: [1,2,4,5,3]

Record 1, descend left to 2, then its children 4 and 5, then return to the root's right child 3.

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now