How to Draw Tree From Preorder Traversal
Construct Tree from given Inorder and Preorder traversals
Let us consider the below traversals:
Inorder sequence: D B E A F C
Preorder sequence: A B D E C F
In a Preorder sequence, leftmost element is the root of the tree. So we know 'A' is root for given sequences. By searching 'A' in Inorder sequence, we can find out all elements on left side of 'A' are in left subtree and elements on right are in right subtree. So we know below structure now.
A / / D B E F C
We recursively follow above steps and get the following tree.
A / / B C / / / / D E F
Algorithm: buildTree()
1) Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below code) to pick next element in next recursive call.
2) Create a new tree node tNode with the data as picked element.
3) Find the picked element's index in Inorder. Let the index be inIndex.
4) Call buildTree for elements before inIndex and make the built tree as left subtree of tNode.
5) Call buildTree for elements after inIndex and make the built tree as right subtree of tNode.
6) return tNode.
Thanks to Rohini and Tushar for suggesting the code.
C++
#include <bits/stdc++.h>
using
namespace
std;
class
node
{
public
:
char
data;
node* left;
node* right;
};
int
search(
char
arr[],
int
strt,
int
end,
char
value);
node* newNode(
char
data);
node* buildTree(
char
in[],
char
pre[],
int
inStrt,
int
inEnd)
{
static
int
preIndex = 0;
if
(inStrt > inEnd)
return
NULL;
node* tNode = newNode(pre[preIndex++]);
if
(inStrt == inEnd)
return
tNode;
int
inIndex = search(in, inStrt, inEnd, tNode->data);
tNode->left = buildTree(in, pre, inStrt, inIndex - 1);
tNode->right = buildTree(in, pre, inIndex + 1, inEnd);
return
tNode;
}
int
search(
char
arr[],
int
strt,
int
end,
char
value)
{
int
i;
for
(i = strt; i <= end; i++)
{
if
(arr[i] == value)
return
i;
}
}
node* newNode(
char
data)
{
node* Node =
new
node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return
(Node);
}
void
printInorder(node* node)
{
if
(node == NULL)
return
;
printInorder(node->left);
cout<<node->data<<
" "
;
printInorder(node->right);
}
int
main()
{
char
in[] = {
'D'
,
'B'
,
'E'
,
'A'
,
'F'
,
'C'
};
char
pre[] = {
'A'
,
'B'
,
'D'
,
'E'
,
'C'
,
'F'
};
int
len =
sizeof
(in) /
sizeof
(in[0]);
node* root = buildTree(in, pre, 0, len - 1);
cout <<
"Inorder traversal of the constructed tree is "
;
printInorder(root);
}
C
#include <stdio.h>
#include <stdlib.h>
struct
node {
char
data;
struct
node* left;
struct
node* right;
};
int
search(
char
arr[],
int
strt,
int
end,
char
value);
struct
node* newNode(
char
data);
struct
node* buildTree(
char
in[],
char
pre[],
int
inStrt,
int
inEnd)
{
static
int
preIndex = 0;
if
(inStrt > inEnd)
return
NULL;
struct
node* tNode = newNode(pre[preIndex++]);
if
(inStrt == inEnd)
return
tNode;
int
inIndex = search(in, inStrt, inEnd, tNode->data);
tNode->left = buildTree(in, pre, inStrt, inIndex - 1);
tNode->right = buildTree(in, pre, inIndex + 1, inEnd);
return
tNode;
}
int
search(
char
arr[],
int
strt,
int
end,
char
value)
{
int
i;
for
(i = strt; i <= end; i++) {
if
(arr[i] == value)
return
i;
}
}
struct
node* newNode(
char
data)
{
struct
node* node = (
struct
node*)
malloc
(
sizeof
(
struct
node));
node->data = data;
node->left = NULL;
node->right = NULL;
return
(node);
}
void
printInorder(
struct
node* node)
{
if
(node == NULL)
return
;
printInorder(node->left);
printf
(
"%c "
, node->data);
printInorder(node->right);
}
int
main()
{
char
in[] = {
'D'
,
'B'
,
'E'
,
'A'
,
'F'
,
'C'
};
char
pre[] = {
'A'
,
'B'
,
'D'
,
'E'
,
'C'
,
'F'
};
int
len =
sizeof
(in) /
sizeof
(in[0]);
struct
node* root = buildTree(in, pre, 0, len - 1);
printf
(
"Inorder traversal of the constructed tree is "
);
printInorder(root);
getchar
();
}
Java
class
Node {
char
data;
Node left, right;
Node(
char
item)
{
data = item;
left = right =
null
;
}
}
class
BinaryTree {
Node root;
static
int
preIndex =
0
;
Node buildTree(
char
in[],
char
pre[],
int
inStrt,
int
inEnd)
{
if
(inStrt > inEnd)
return
null
;
Node tNode =
new
Node(pre[preIndex++]);
if
(inStrt == inEnd)
return
tNode;
int
inIndex = search(in, inStrt, inEnd, tNode.data);
tNode.left = buildTree(in, pre, inStrt, inIndex -
1
);
tNode.right = buildTree(in, pre, inIndex +
1
, inEnd);
return
tNode;
}
int
search(
char
arr[],
int
strt,
int
end,
char
value)
{
int
i;
for
(i = strt; i <= end; i++) {
if
(arr[i] == value)
return
i;
}
return
i;
}
void
printInorder(Node node)
{
if
(node ==
null
)
return
;
printInorder(node.left);
System.out.print(node.data +
" "
);
printInorder(node.right);
}
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
char
in[] =
new
char
[] {
'D'
,
'B'
,
'E'
,
'A'
,
'F'
,
'C'
};
char
pre[] =
new
char
[] {
'A'
,
'B'
,
'D'
,
'E'
,
'C'
,
'F'
};
int
len = in.length;
Node root = tree.buildTree(in, pre,
0
, len -
1
);
System.out.println(
"Inorder traversal of constructed tree is : "
);
tree.printInorder(root);
}
}
Python
class
Node:
def
__init__(
self
, data):
self
.data
=
data
self
.left
=
None
self
.right
=
None
def
buildTree(inOrder, preOrder, inStrt, inEnd):
if
(inStrt > inEnd):
return
None
tNode
=
Node(preOrder[buildTree.preIndex])
buildTree.preIndex
+
=
1
if
inStrt
=
=
inEnd :
return
tNode
inIndex
=
search(inOrder, inStrt, inEnd, tNode.data)
tNode.left
=
buildTree(inOrder, preOrder, inStrt, inIndex
-
1
)
tNode.right
=
buildTree(inOrder, preOrder, inIndex
+
1
, inEnd)
return
tNode
def
search(arr, start, end, value):
for
i
in
range
(start, end
+
1
):
if
arr[i]
=
=
value:
return
i
def
printInorder(node):
if
node
is
None
:
return
printInorder(node.left)
print
node.data,
printInorder(node.right)
inOrder
=
[
'D'
,
'B'
,
'E'
,
'A'
,
'F'
,
'C'
]
preOrder
=
[
'A'
,
'B'
,
'D'
,
'E'
,
'C'
,
'F'
]
buildTree.preIndex
=
0
root
=
buildTree(inOrder, preOrder,
0
,
len
(inOrder)
-
1
)
print
"Inorder traversal of the constructed tree is"
printInorder(root)
C#
using
System;
public
class
Node {
public
char
data;
public
Node left, right;
public
Node(
char
item)
{
data = item;
left = right =
null
;
}
}
class
GFG {
public
Node root;
public
static
int
preIndex = 0;
public
virtual
Node buildTree(
char
[] arr,
char
[] pre,
int
inStrt,
int
inEnd)
{
if
(inStrt > inEnd) {
return
null
;
}
Node tNode =
new
Node(pre[preIndex++]);
if
(inStrt == inEnd) {
return
tNode;
}
int
inIndex = search(arr, inStrt,
inEnd, tNode.data);
tNode.left = buildTree(arr, pre, inStrt, inIndex - 1);
tNode.right = buildTree(arr, pre, inIndex + 1, inEnd);
return
tNode;
}
public
virtual
int
search(
char
[] arr,
int
strt,
int
end,
char
value)
{
int
i;
for
(i = strt; i <= end; i++) {
if
(arr[i] == value) {
return
i;
}
}
return
i;
}
public
virtual
void
printInorder(Node node)
{
if
(node ==
null
) {
return
;
}
printInorder(node.left);
Console.Write(node.data +
" "
);
printInorder(node.right);
}
public
static
void
Main(
string
[] args)
{
GFG tree =
new
GFG();
char
[] arr =
new
char
[] {
'D'
,
'B'
,
'E'
,
'A'
,
'F'
,
'C'
};
char
[] pre =
new
char
[] {
'A'
,
'B'
,
'D'
,
'E'
,
'C'
,
'F'
};
int
len = arr.Length;
Node root = tree.buildTree(arr, pre, 0, len - 1);
Console.WriteLine(
"Inorder traversal of "
+
"constructed tree is : "
);
tree.printInorder(root);
}
}
Output:
Inorder traversal of the constructed tree is D B E A F C
Time Complexity: O(n^2). Worst case occurs when tree is left skewed. Example Preorder and Inorder traversals for worst case are {A, B, C, D} and {D, C, B, A}.
Efficient Approach :
We can optimize the above solution using hashing (unordered_map in C++ or HashMap in Java). We store indexes of inorder traversal in a hash table. So that search can be done O(1) time.
C++
#include <bits/stdc++.h>
using
namespace
std;
struct
Node {
char
data;
struct
Node* left;
struct
Node* right;
};
struct
Node* newNode(
char
data)
{
struct
Node* node =
new
Node;
node->data = data;
node->left = node->right = NULL;
return
(node);
}
struct
Node* buildTree(
char
in[],
char
pre[],
int
inStrt,
int
inEnd, unordered_map<
char
,
int
>& mp)
{
static
int
preIndex = 0;
if
(inStrt > inEnd)
return
NULL;
char
curr = pre[preIndex++];
struct
Node* tNode = newNode(curr);
if
(inStrt == inEnd)
return
tNode;
int
inIndex = mp[curr];
tNode->left = buildTree(in, pre, inStrt, inIndex - 1, mp);
tNode->right = buildTree(in, pre, inIndex + 1, inEnd, mp);
return
tNode;
}
struct
Node* buldTreeWrap(
char
in[],
char
pre[],
int
len)
{
unordered_map<
char
,
int
> mp;
for
(
int
i = 0; i < len; i++)
mp[in[i]] = i;
return
buildTree(in, pre, 0, len - 1, mp);
}
void
printInorder(
struct
Node* node)
{
if
(node == NULL)
return
;
printInorder(node->left);
printf
(
"%c "
, node->data);
printInorder(node->right);
}
int
main()
{
char
in[] = {
'D'
,
'B'
,
'E'
,
'A'
,
'F'
,
'C'
};
char
pre[] = {
'A'
,
'B'
,
'D'
,
'E'
,
'C'
,
'F'
};
int
len =
sizeof
(in) /
sizeof
(in[0]);
struct
Node* root = buldTreeWrap(in, pre, len);
printf
(
"Inorder traversal of the constructed tree is "
);
printInorder(root);
}
Output:
Inorder traversal of the constructed tree is D B E A F C
Time Complexity : O(n)
Another approach :
Use the fact that InOrder traversal is Left-Root-Right and PreOrder traversal is Root-Left-Right. Also, first node in the PreOrder traversal is always the root node and the first node in the InOrder traversal is the leftmost node in the tree.
Maintain two data-structures : Stack (to store the path we visited while traversing PreOrder array) and Set (to maintain the node in which the next right subtree is expected).
1. Do below until you reach the leftmost node.
Keep creating the nodes from PreOrder traversal
If the stack's topmost element is not in the set, link the created node to the left child of stack's topmost element (if any), without popping the element.
Else link the created node to the right child of stack's topmost element. Remove the stack's topmost element from the set and the stack.
Push the node to a stack.
2. Keep popping the nodes from the stack until either the stack is empty, or the topmost element of stack compares to the current element of InOrder traversal. Once the loop is over, push the last node back into the stack and into the set.
3. Goto Step 1.
import
java.util.*;
public
class
TreeNode {
int
val;
TreeNode left;
TreeNode right;
TreeNode(
int
x) { val = x; }
}
class
BinaryTree {
static
Set<TreeNode> set =
new
HashSet<>();
static
Stack<TreeNode> stack =
new
Stack<>();
public
TreeNode buildTree(
int
[] preorder,
int
[] inorder)
{
TreeNode root =
null
;
for
(
int
pre =
0
, in =
0
; pre < preorder.length;) {
TreeNode node =
null
;
do
{
node =
new
TreeNode(preorder[pre]);
if
(root ==
null
) {
root = node;
}
if
(!stack.isEmpty()) {
if
(set.contains(stack.peek())) {
set.remove(stack.peek());
stack.pop().right = node;
}
else
{
stack.peek().left = node;
}
}
stack.push(node);
}
while
(preorder[pre++] != inorder[in] && pre < preorder.length);
node =
null
;
while
(!stack.isEmpty() && in < inorder.length &&
stack.peek().val == inorder[in]) {
node = stack.pop();
in++;
}
if
(node !=
null
) {
set.add(node);
stack.push(node);
}
}
return
root;
}
void
printInorder(TreeNode node)
{
if
(node ==
null
)
return
;
printInorder(node.left);
System.out.print(node.val +
" "
);
printInorder(node.right);
}
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
int
in[] =
new
int
[] {
9
,
8
,
4
,
2
,
10
,
5
,
10
,
1
,
6
,
3
,
13
,
12
,
7
};
int
pre[] =
new
int
[] {
1
,
2
,
4
,
8
,
9
,
5
,
10
,
10
,
3
,
6
,
7
,
12
,
13
};
int
len = in.length;
TreeNode root = tree.buildTree(pre, in);
tree.printInorder(root);
}
}
Output:
9 8 4 2 10 5 10 1 6 3 13 12 7
Thanks Hardik Agarwal for suggesting this approach.
Construct a Binary Tree from Postorder and Inorder
Please write comments if you find any bug in above codes/algorithms, or find other ways to solve the same problem.
0 0
You Might Also Like
Subscribe to Our Newsletter
hennessywhavillat81.blogspot.com
Source: https://tutorialspoint.dev/data-structure/binary-tree-data-structure/construct-tree-from-given-inorder-and-preorder-traversal