Binary Tree Preorder Traversal
1 approach, code in every language
Problem description
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
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Survey Order Of A Ventilation Split is our own problem on the technique behind Binary Tree Preorder Traversal: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free