← DiffPush

Preorder Traversal of Binary Tree

Baseline Binary Trees · Traversals O(n) · O(n)

Root-First Plant Audit

A botanical survey drone maps an orchard laid out as a binary grafting tree. Regulations require the auditor to log each grafted plant before descending into its two branch lineages, always taking the left lineage before the right. The drone's log, read top to bottom, becomes the orchard's master inventory.

Input: The root of a binary tree given as a level-order array where null marks a missing child.

Output: Return an array of node values in preorder: visit the node, then its left subtree, then its right subtree.

Constraints

Examples

Example 1

Input: {"tree":[1,2,3,4,5,null,6]}
Output: [1,2,4,5,3,6]
Root 1 first, then the whole left subtree {2,4,5}, then right subtree {3,6}.

Example 2

Input: {"tree":[7]}
Output: [7]
A lone node is its own preorder sequence.

Solve this in your browser →

Also on LeetCode ↗