Is Array a Preorder of Some ‌Binary Tree - Problem

Given a 0-indexed integer 2D array nodes, your task is to determine if the given array represents the preorder traversal of some binary tree.

For each index i, nodes[i] = [id, parentId], where:

  • id is the id of the node at index i
  • parentId is the id of its parent in the tree (if the node has no parent, then parentId == -1)

Return true if the given array represents the preorder traversal of some tree, and false otherwise.

Note: The preorder traversal of a tree is a recursive way to traverse a tree in which we first visit the current node, then we do the preorder traversal for the left child, and finally, we do it for the right child.

Input & Output

Example 1 — Valid Preorder
$ Input: nodes = [[1,-1],[2,1],[3,2]]
Output: true
💡 Note: This represents preorder traversal of tree: 1 is root, 2 is left child of 1, 3 is left child of 2. Preorder visits: 1 → 2 → 3, matching the input order.
Example 2 — Invalid Parent-Child
$ Input: nodes = [[1,-1],[2,1],[3,1],[4,2],[5,3]]
Output: false
💡 Note: After visiting node 4 (child of 2), we cannot visit node 5 (child of 3) because we would have already finished the left subtree of 1. This violates preorder properties.
Example 3 — Multiple Roots
$ Input: nodes = [[1,-1],[2,-1]]
Output: false
💡 Note: A binary tree can have only one root node. Having multiple nodes with parentId = -1 makes it invalid.

Constraints

  • 0 ≤ nodes.length ≤ 105
  • nodes[i].length == 2
  • 1 ≤ id, parentId ≤ 105
  • parentId == -1 if and only if the node is the root

Visualization

Tap to expand
Is Array a Preorder of Some Binary Tree INPUT nodes = [[1,-1],[2,1],[3,2]] [1,-1] i=0 [2,1] i=1 [3,2] i=2 Expected Tree Structure: 1 root 2 left 3 left ALGORITHM STEPS 1 Use Stack Track ancestors during traversal simulation 2 Process Each Node Pop until parent found or stack empty 3 Validate Parent Check if parent matches stack top (or -1 for root) 4 Push Current Node Add node to stack and continue to next Stack Trace: [1] --> [1,2] --> [1,2,3] OK OK OK FINAL RESULT Valid Preorder Traversal! 1 2 3 Preorder: 1 --> 2 --> 3 Output: true Key Insight: In preorder traversal, each node must appear right after its parent or after all descendants of a sibling. Use a stack to simulate the traversal path. When processing node i, pop until finding its parent on stack. If parent not found (and not root), the array is not a valid preorder. Time: O(n), Space: O(n). TutorialsPoint - Is Array a Preorder of Some Binary Tree | Optimal Solution (Stack-based)
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen