Problem Description
Given a 0-indexed 2D integer array nodes where each element is of the form [id, parentId] (with parentId == -1 indicating the root), determine if the array represents the preorder traversal of some binary tree. In a preorder traversal we visit the current node first, then recursively traverse its left child followed by its right child. Although the input always forms a valid binary tree structure (each node having at most two children), the order in which they appear must match one possible preorder traversal.
Key Insights
- The first node must be the root (its parentId must be -1).
- In a preorder traversal, a node always appears before its children.
- When moving to a new node in the sequence, it should either be the left child of the most recent node or be part of the right subtree of one of the ancestors.
- A stack can simulate the DFS recursion: if the current node’s parent matches the top of the stack, it is the next child; otherwise, pop the stack until a match is found.
- If no matching parent is found and the node’s parentId is not -1, the sequence cannot be a valid preorder.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes.
Space Complexity: O(n) in the worst case, due to the auxiliary stack used in the simulation.
Solution
We simulate a preorder DFS traversal using a stack. We iterate over each node in the given sequence and check:
- For the first node, ensure its parentId is -1 (it must be the root).
- For every subsequent node:
- If the top of the stack (which represents the current context in the DFS) has an id that matches the node’s parentId, then this node is a child of the current context.
- Otherwise, pop from the stack because we are done processing the subtree and backtrack to a node that could be the parent.
- If, after backtracking, no node’s id on the stack matches the node’s parentId (and the parentId is not -1), the sequence cannot represent a valid preorder traversal.
- Push the current node’s id onto the stack.
This process ensures that the given order adheres to the requirement that a node’s children appear consecutively after it in a valid preorder traversal of a binary tree.