Is Array a Preorder of Some Binary Tree - Problem
You're given a 2D array representing nodes of a potential binary tree, where each node is defined as
In a preorder traversal, we visit nodes in this specific order: root → left subtree → right subtree. This means that for any node, all nodes in its left subtree must appear before any nodes in its right subtree in the traversal sequence.
Key Rules:
[id, parentId]. Your task is to determine if this array represents a valid preorder traversal of some binary tree.In a preorder traversal, we visit nodes in this specific order: root → left subtree → right subtree. This means that for any node, all nodes in its left subtree must appear before any nodes in its right subtree in the traversal sequence.
Key Rules:
- Each node has a unique
id - Root node has
parentId = -1 - Each node can have at most 2 children (left and right)
- The array order must follow preorder traversal rules
true if the given array represents a valid preorder traversal, false otherwise. Input & Output
example_1.py — Valid Binary Tree
$
Input:
[[1,-1],[2,1],[3,1]]
›
Output:
true
💡 Note:
This represents a valid binary tree with root 1 and children 2,3. The preorder traversal would be 1→2→3, which matches the input order.
example_2.py — Invalid Preorder
$
Input:
[[1,-1],[3,1],[2,1]]
›
Output:
false
💡 Note:
While this could form a valid binary tree, the order is wrong for preorder traversal. Preorder should be 1→2→3, but we have 1→3→2.
example_3.py — Too Many Children
$
Input:
[[1,-1],[2,1],[3,1],[4,1]]
›
Output:
false
💡 Note:
Node 1 has three children (2,3,4), which violates the binary tree constraint of maximum 2 children per node.
Constraints
- 1 ≤ nodes.length ≤ 105
- nodes[i].length == 2
- 1 ≤ nodes[i][0] ≤ 106
- -1 ≤ nodes[i][1] ≤ 106
- All node IDs are unique
- There is exactly one node with parentId = -1 (root)
Visualization
Tap to expand
Understanding the Visualization
1
Start with Root
Initialize with the root node (parentId = -1)
2
Track Path
Use stack to maintain current path from root
3
Validate Children
Each new node must have its parent in current stack path
4
Update Stack
Adjust stack based on whether this is first or second child
Key Takeaway
🎯 Key Insight: A valid preorder traversal can be simulated using a stack - we can always determine if the next node belongs by checking if its parent exists in our current traversal path.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code