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 TreeInput: [[1,-1],[2,1],[3,2]]Node-Parent Pairs1: root2: child of 13: child of 21Root2Left of 13Left of 2Preorder Traversal:Visit: 1 → 2 → 3Matches input orderResult: true ✓Check if node sequence follows preorder properties
Understanding the Visualization
1
Input Analysis
Parse parent-child relationships from nodes array
2
Preorder Property
Check if sequence follows preorder traversal rules
3
Validation Result
Return true if valid, false otherwise
Key Takeaway
🎯 Key Insight: Use stack to simulate preorder traversal - each node's parent must be at stack top when processing
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