Problem
You are given a binary tree represented as childNodes, where node 1 is the root. Write a solution function that performs a preorder traversal of the binary tree and returns the node numbers in the order they are visited.
Concept Explanation
Tree traversal refers to the process of visiting each node in a binary tree in a specific order.
A binary tree is a tree where every node has at most two child nodes, commonly referred to as the left and right child.
In preorder traversal, the nodes are visited in the following order:
- Visit the root node.
- Recursively traverse the left subtree in preorder.
- Recursively traverse the right subtree in preorder.
Consider the binary tree shown below:

The preorder traversal is as follows:
-
Start at the root node,
1.

-
Traverse the left subtree starting with node
2.

-
Visit node
5in the left subtree of node2.

-
Attempt to traverse the left child of node
5. Since it has no left child, move to its right child, node4.

-
After visiting node
4, return to node2and traverse its right subtree, starting with node7.

-
Traverse node
7's left child (6) and its right child (8). After finishing the left subtree of node1, move to its right child, node3.

Thus, the preorder traversal of the given tree is:
1 → 2 → 5 → 4 → 7 → 6 → 8 → 3.
Constraints
childNodesis a 2D array representing the left and right child nodes for each node:- The length of
childNodesis between 2 and 100,000. childNodes[i - 1][0]represents the left child of nodei.childNodes[i - 1][1]represents the right child of nodei.- If a node does not have a left or right child, the corresponding value is
-1.
- The length of
Test Case
| Test Case Number | childNodes | return |
|---|---|---|
| 1 | [[2,3],[5,7],[-1,-1],[-1,-1],[-1,4],[-1,8],[6,-1],[-1,-1]] | [1,2,5,4,7,6,8,3] |
| 2 | [[8,6],[-1,-1],[5,-1],[-1,-1],[-1,-1],[10,9],[2,-1],[4,-1],[7,3],[-1,-1]] | [1,8,4,6,10,9,7,2,3,5] |
| 3 | [[5,-1],[3,-1],[-1,-1],[-1,2],[-1,4]] | [1,5,4,2,3] |
Explanation for Test Case 1
- This test case matches the example shown in the concept section.
Explanation for Test Case 2

- Preorder traversal:
1 → 8 → 4 → 6 → 10 → 9 → 7 → 2 → 3 → 5.
Explanation for Test Case 3

- Preorder traversal:
1 → 5 → 4 → 2 → 3.