Construct Binary Tree from Preorder and Inorder Traversal
To build the binary tree from given preorder and inorder traversal arrays, you can follow these steps:
- Start with the first element of the preorder array, which will be the root of the tree.
- Find the root in the inorder array. The elements to the left of the root in the inorder array will form the left subtree, and the elements to the right of the root will form the right subtree.
- Recursively apply the above steps for the left and right subtrees.
Here’s the Python code:
|
|
Here’s a brief explanation of the code:
- The function
build
constructs the tree recursively using the given boundaries in the preorder and inorder arrays. - We use a dictionary
inorder_dict
to quickly find the index of an element in the inorder array. - The recursive process continues by dividing the arrays into left and right subtrees until the boundaries are not valid (i.e., the base case when
pre_left > pre_right
orin_left > in_right
).