Binary Tree Preorder Traversal
Updated
Problem statement
You are given a binary tree stored in the integer array tree. The first entry is the root. For a node at index i, its left child is at 2 * i + 1 and its right child is at 2 * i + 2. The value -1 marks a missing node.
Return the values of the existing nodes in preorder: visit the root, then the left subtree, then the right subtree.
If the array is empty or its root is -1, the tree is empty, so return an empty array.
Function
preorderTraversal(tree: int[]) → int[]Examples
Example 1
tree = [1,2,3,-1,4,5,6]return = [1,2,4,3,5,6]Start at the root 1. Next comes its left subtree: 2, which has no left child, then the right child of that node, 4. Then comes the root's right subtree: 3, then its children 5 and 6. Read in that order, these values are the answer.
Example 2
tree = [7,-1,9,-1,-1,8,10]return = [7,9,8,10]The left child of 7 is missing, so preorder moves straight to the right subtree, rooted at 9. That subtree gives its root, then its left child, then its right child. So the answer is the root followed by those subtree values, in that order.
Constraints
0 <= tree.length <= 10^5.- Each array entry is either
-1or an integer in the range[0, 10^9]. - Every node that exists, other than the root, has a parent that also exists.
- Indexes beyond
tree.length - 1represent missing nodes.
More Anduril interview questions
- Add Word and Suffix SearchONSITE INTERVIEW · Seen Aug 2026
- Operator-First Array CalculatorONSITE INTERVIEW · Seen Aug 2026
- Daily TemperaturesONSITE INTERVIEW · Seen Jun 2024
- Highlighted Context WindowsONSITE INTERVIEW · Seen Jun 2024
- Pacific Atlantic Water FlowPHONE SCREEN · Seen Aug 2026
- Choose the Front Football TeamPHONE SCREEN · Seen May 2026
- Maximum Visible DronesPHONE SCREEN · Seen Jun 2024
- Build a Sorted Circular Singly Linked ListPHONE SCREEN · Seen Feb 2024
- Sparse Vector Dot ProductPHONE SCREEN · Seen Apr 2021
Similar questions at other companies
- All Root-to-Leaf Paths in a Binary TreeGoogle · ONSITE INTERVIEWGoogle interview questions
- Preorder, Inorder and Postorder of a Binary TreeCapital One · OA · ONSITE INTERVIEWCapital One interview questions
- Render a Comment HierarchyAmazon · ONSITE INTERVIEW
- Kth Smallest Element in a Binary Search TreeSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Delete a Filesystem TreeDatadog · PHONE SCREEN · ONSITE INTERVIEWDatadog interview questions
- Flatten and Reconstruct an Ordered TreeThe Walt Disney Company · ONSITE INTERVIEWThe Walt Disney Company interview questions
- Inorder, Preorder and Postorder TraversalsAMD · ONSITE INTERVIEWAMD interview questions
- Compare N-Ary Tree Leaf SequencesNavan · ONSITE INTERVIEWNavan interview questions
- Flatten JSON into Repeated Key-Value PairsKlaviyo · ONSITE INTERVIEWKlaviyo interview questions
- Kth Smallest Value in a BSTExpedia · PHONE SCREEN · ONSITE INTERVIEWExpedia interview questions