Construct Binary Tree From Preorder And Inorder Traversal
To solve this coding challenge, you need to construct a binary tree from given preorder and inorder traversal lists. Here's a detailed explanation and pseudocode to help you understand how you can accomplish this task.
Explanation
Preorder Traversal
In a preorder traversal, you visit nodes in the following order:- Root
- Left Subtree
- Right Subtree For example, given
-
The first element
3
-
The subtree rooted at
3
9
20, 15, 7
- Left Subtree
- Root
- Right Subtree For example, given
-
Nodes to the left of
3
(9)
-
Nodes to the right of
3
(15, 20, 7)
- Identify the root from the first element of the preorder list.
- Find the root's index in the inorder list, which helps in separating the left and right subtrees.
- Recursively perform the above steps to construct left and right subtrees.
-
Base Condition
: If the inorder list is empty, return
None
- Root Identification :
- Remove the first element from the preorder list; this is the current root.
- Find this rootβs index in the inorder list.
- Subtree Construction :
- Elements to the left of the root in the inorder list form the left subtree.
- Elements to the right form the right subtree.
- Recursive Construction :
- Recursively build the left subtree by passing the corresponding segments of preorder and inorder lists.
- Recursively build the right subtree similarly.
[3, 9, 20, 15, 7]
Inorder Traversal
In an inorder traversal, you visit nodes in the following order:[9, 3, 15, 20, 7]
Steps to Solve the Challenge
Detailed Steps in Pseudocode
To clarify these steps, we break down the process into small and very explicit steps.Pseudocode
// Function to build the tree from preorder and inorder traversal lists
function buildTree(preorder, inorder):
// Base case: if inorder list is empty, return None
if inorder is empty:
return None
// Get the root value from the preorder list (first element)
root_value = preorder.pop(0)
// Find the index of the root in the inorder list
root_index = findIndex(inorder, root_value)
// Create the root node
root_node = TreeNode(root_value)
// Build the left subtree by taking elements before root_index in inorder
root_node.left = buildTree(preorder, inorder[0:root_index])
// Build the right subtree by taking elements after root_index in inorder
root_node.right = buildTree(preorder, inorder[root_index + 1:end])
// Return the constructed root_node
return root_node
// Helper function to find the index of a value in a list
function findIndex(list, value):
for i from 0 to length(list) - 1:
if list[i] == value:
return i
return -1
In the pseudocode:
-
buildTree
-
preorder.pop(0)
-
findIndex
-
When we make recursive calls to
buildTree