FastPrepBinary Tree Preorder Traversal

Binary Tree Preorder Traversal

Anduril logoAnduril● EasyFULLTIMEONSITE INTERVIEW

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 -1 or 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 - 1 represent missing nodes.

More Anduril interview questions

Similar questions at other companies

All Anduril interview questionsSee Anduril hiring insights
Saved
class Solution {
    public int[] preorderTraversal(int[] tree) {
        // write your code here
    }
}
Checking account…