using
System;
using
System.Collections;
using
System.Collections.Generic;
public
class
Node{
public
int
data;
public
Node left, right;
public
Node(
int
item){
data = item;
left = right =
null
;
}
}
class
GFG{
public
static
int
preIdx = 0;
public
static
Dictionary<
int
,
int
> m =
new
Dictionary<
int
,
int
>();
public
static
Node buildBTRec(
int
[] In,
int
[] pre,
int
inStart,
int
inEnd){
if
(inStart > inEnd)
return
null
;
int
curr = pre[preIdx];
preIdx += 1;
Node temp =
new
Node(curr);
if
(inStart == inEnd)
return
temp;
int
idx = m[curr];
temp.left = buildBTRec(In, pre, inStart, idx-1);
temp.right = buildBTRec(In, pre, idx+1, inEnd);
return
temp;
}
public
static
Node buildBST(
int
[] pre,
int
n){
int
[] In =
new
int
[n];
for
(
int
i = 0; i<n; i++){
In[i] = pre[i];
}
Array.Sort(In);
for
(
int
i = 0; i<n; i++){
m[In[i]] = i;
}
return
buildBTRec(In, pre, 0, n-1);
}
public
static
void
inorderTraversal(Node root){
if
(root ==
null
)
return
;
inorderTraversal(root.left);
Console.Write(root.data +
" "
);
inorderTraversal(root.right);
}
public
static
void
Main(
string
[] args){
int
[] pre = {100, 20, 10, 30, 200, 150, 300};
int
n = pre.Length;
Node root = buildBST(pre, n);
Console.WriteLine(
"Inorder Traversal of the tree is : "
);
inorderTraversal(root);
}
}