Skip to main content

Binary Tree Preorder Traversal

Easy
Data Structures and Algorithms
Editorial
Topics:
Binary Tree
Tree
Depth-First Search

A binary tree is a structure in which each node has a value and up to two children: a left child and a right child. root refers to the top node of the tree; a missing child is represented by null in the level-order input, and an empty tree is represented by [].

Traverse the tree in preorder: visit the current node first, then traverse its entire left subtree, and finally traverse its entire right subtree. Return a list containing the visited node values in that order.

Do not modify the tree. If root is empty, return an empty list.

Example 1:

Input: root = [8,3,null,1,6,null,null,4,7]
Output: [8,3,1,6,4,7]
Explanation: The root is visited before its descendants; within the left subtree, 3 comes before 1 and 6, and 6 comes before its children 4 and 7.

Example 2:

Input: root = [5]
Output: [5]
Explanation: A tree with one node has that node as its entire preorder traversal.

Example 3:

Input: root = [10,null,12,null,14]
Output: [10,12,14]
Explanation: Each node has only a right child, so preorder visits the nodes from the root down that right-hand chain.

Constraints:

  • 0 <= number of nodes in root <= 100
  • -100 <= each node value <= 100
  • Each node has at most one left child and at most one right child
  • root is a valid binary tree encoded in level order, using null for missing children

Need help or want more practice?

Practise in an interviewGet AI Coach help