2764. Is Array a Preorder of Some βBinary Tree π
Description
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 the index i and 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.
Example 1:
Input: nodes = [[0,-1],[1,0],[2,0],[3,2],[4,2]] Output: true Explanation: The given nodes make the tree in the picture below. We can show that this is the preorder traversal of the tree, first we visit node 0, then we do the preorder traversal of the right child which is [1], then we do the preorder traversal of the left child which is [2,3,4].
Example 2:
Input: nodes = [[0,-1],[1,0],[2,0],[3,1],[4,1]] Output: false Explanation: The given nodes make the tree in the picture below. For the preorder traversal, first we visit node 0, then we do the preorder traversal of the right child which is [1,3,4], but we can see that in the given order, 2 comes between 1 and 3, so, it's not the preorder traversal of the tree.
Constraints:
1 <= nodes.length <= 105nodes[i].length == 20 <= nodes[i][0] <= 105-1 <= nodes[i][1] <= 105- The input is generated such that
nodesmake a binary tree.
Solutions
Solution 1
Thinking
Given nodes with parent pointers, decide whether the list is a preorder of some binary tree. Rebuilding and walking the tree would check the same fact with extra structure.
Build child lists from the parents, then DFS from the root: the current node must equal item \(k\) of the list, then recurse in child order. At the end \(k\) must equal the number of nodes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |

