📘
Construct Binary Tree from Preorder and Inorder
MediumTrees
Given preorder and inorder traversal arrays, construct the binary tree.
Output the level-order traversal of the constructed tree, space-separated.
Example:
Input:
3,9,20,15,7 9,3,15,20,7
Output:
3 9 20 null null 15 7
Reasoning:
- The preorder traversal array
[3, 9, 20, 15, 7]represents the order in which nodes are visited: root, left subtree, right subtree. The first element3is the root node. - The inorder traversal array
[9, 3, 15, 20, 7]represents the order in which nodes are visited: left subtree, root, right subtree. This helps to identify the left and right child nodes of the root3, which are9and20respectively. - The left subtree of
3only contains9, and the right subtree of3is constructed from the remaining elements[15, 20, 7]in the inorder array, with20as the root,15as its left child, and7as its right child. - The constructed binary tree is then traversed level-by-level to produce the output:
3(root),9(left child of3),20(right child of3),null(no left child of9),null(no right child of9),15(left child of20),7(right child of20).
Constraints:
- 1 <= length <= 3000
- All values unique
- -3000 <= values <= 3000
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.