Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Implement preorder traversalE02. Implement inorder traversalE03. Implement postorder traversalE

Problem No 1

Implement preorder traversal

Easy

6 minute session

Summary

Write a function to perform a preorder (root-left-right) traversal of a binary tree and return the list of visited node values.

Problem statement

Given the root of a binary tree, implement a function preorder(root) that returns a list of node values visited in preorder (root, left, right). The tree nodes are represented by the provided Node class. The function should handle empty trees (None) and return an empty list for them.

Task

Implement preorder traversal that visits root then left subtree then right subtree. Return values as a list in traversal order.

Examples

Small tree

Input

preorder(Node(1, Node(2), Node(3)))

Output

[1, 2, 3]

Explanation

Visit root 1, then left child 2, then right child 3.

Input format

A single argument: root (Node or None).

Output format

A list of integers representing node values in preorder order.

Constraints

Tree node count <= 10^4. Node values are integers. Use recursion or iteration. Do not print; return the list.

Samples

Sample input 0

preorder(None)

Sample output 0

[]

Explanation 0

Empty tree returns empty list.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:43 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.