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:
idis the id of the node at indexiparentIdis the id of its parent in the tree (if the node has no parent, thenparentId == -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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code