Build Binary Tree from Preorder and Inorder Traversal
Explore how to build a binary tree by using preorder and inorder traversal arrays. Learn to analyze the relationship between these traversals and implement an algorithm to reconstruct the tree, improving your understanding of tree structures and depth-first search techniques.
We'll cover the following...
Statement
Create a binary tree from two integer arrays, pOrder and iOrder, where pOrder represents a preorder traversal of a binary tree, and iOrder represents an inorder traversal of the same tree.
Constraints:
-
pOrder.length,iOrder.length iOrder.lengthpOrder.length-
pOrder[i],iOrder[i] pOrderandiOrderconsist of unique values.- Each value of
iOrderalso appears inpOrderand vice versa.
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:
Build Binary Tree from Preorder and Inorder Traversal
Select the correct binary tree constructed from preorder and inorder traversal:
preorder = [1, 12, 15, 6, 9, 5, 2]
inorder = [15, 12, 6, 1, 5, 9, 2]
1
/ \
12 9
/ \ / \
15 6 5 2
12
/ \
1 9
/ \ / \
15 6 5 2
15
/ \
12 9
/ \ / \
1 6 5 2
9
/ \
1 12
/ \ / \
15 6 5 2
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
import java.util.*;import ds_v1.BinaryTree.TreeNode;// Definiton of a binary tree node class// class TreeNode<T> {// T data;// TreeNode<T> left;// TreeNode<T> right;// TreeNode(T data) {// this.data = data;// this.left = null;// this.right = null;// }// }public class Solution {public static TreeNode<Integer> buildTree(int[] pOrder, int[] iOrder) {// Replace this placeholder return statement with your codereturn new TreeNode<Integer>(-1);}}