Construct Tree from given Inorder and Preorder traversals
Page 1 of 1
Construct Tree from given Inorder and Preorder traversals
public class Node{
private int value;
private Node left;
private Node right;
public Node(int v, Node l, Node r){
value=v;
left=l;
right=r;
}
}
public class Build{
public Node buildTree(int in[], int pre[], int start, int end){
static int preIndex=0;
if(start>end)
return null;
Node temp=new Node(pre[preIndex++],null,null);
if(start==end)
return temp;
int inIndex=search(in, start,end, temp.value);
temp.left=buildTree(in, pre, start, inIndex-1);
temp.right=buildTree(int,pre,inIndex+1,end);
return temp;
}
public int search(int[] in, int start, int end, int data){
for(int i=start;i<=end;i++){
if(in[i]==data)
return i;
}
}
}
private int value;
private Node left;
private Node right;
public Node(int v, Node l, Node r){
value=v;
left=l;
right=r;
}
}
public class Build{
public Node buildTree(int in[], int pre[], int start, int end){
static int preIndex=0;
if(start>end)
return null;
Node temp=new Node(pre[preIndex++],null,null);
if(start==end)
return temp;
int inIndex=search(in, start,end, temp.value);
temp.left=buildTree(in, pre, start, inIndex-1);
temp.right=buildTree(int,pre,inIndex+1,end);
return temp;
}
public int search(int[] in, int start, int end, int data){
for(int i=start;i<=end;i++){
if(in[i]==data)
return i;
}
}
}
skyboard- Posts : 31
Join date : 2011-09-03
Similar topics
» Write a program to determine if a binary tree is well ordered
» Level order traverse of a tree
» Jude whether a binary tree is well ordered
» To get mirror image of a binary tree
» You are given a TreeNode, and you have to write an algorithm which will return the no. of nodes in the tree.
» Level order traverse of a tree
» Jude whether a binary tree is well ordered
» To get mirror image of a binary tree
» You are given a TreeNode, and you have to write an algorithm which will return the no. of nodes in the tree.
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|