Created
July 4, 2017 16:44
-
-
Save anil477/d5ac551e24dc0b9c9159f262273966ba to your computer and use it in GitHub Desktop.
Print Postorder traversal from given Inorder and Preorder traversals without constructing the tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node | |
{ | |
char data; | |
Node left, right; | |
Node(char item) | |
{ | |
data = item; | |
left = right = null; | |
} | |
} | |
class BinaryTree | |
{ | |
Node root; | |
int preIndex = 0; | |
void buildTree(char in[], char pre[], int inStrt, int inEnd) | |
{ | |
if (inStrt > inEnd) | |
return; | |
/* Pick current node from Preorder traversal using preIndex | |
and increment preIndex */ | |
Node tNode = new Node(pre[preIndex++]); | |
/* If this node has no children then return */ | |
if (inStrt == inEnd){ | |
System.out.println(tNode.data + " "); | |
return; | |
} | |
/* Else find the index of this node in Inorder traversal */ | |
int inIndex = search(in, inStrt, inEnd, tNode.data); | |
/* Using index in Inorder traversal, construct left and | |
right subtress */ | |
buildTree(in, pre, inStrt, inIndex - 1); | |
buildTree(in, pre, inIndex + 1, inEnd); | |
System.out.println(tNode.data + " "); | |
} | |
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; | |
} | |
// driver program to test above functions | |
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; | |
tree.buildTree(in, pre, 0, len - 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment