Construct a BST from inorder and preorder traversal string
Solution:
Let us consider the below traversals:
Inorder sequence: D B E A F C
Preorder sequence: A B D E C F
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
struct node* buildTree(char in[], char pre[], int inStrt, int inEnd) { static int preIndex = 0; if(inStrt > inEnd) return NULL; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ struct node *tNode = newNode(pre[preIndex++]); /* If this node has no children then return */ if(inStrt == inEnd) return tNode; /* 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 */ tNode->left = buildTree(in, pre, inStrt, inIndex-1); tNode->right = buildTree(in, pre, inIndex+1, inEnd); return tNode; }
Complexity:
time - O(n^2)Links and credits:
space - O(n)
http://www.careercup.com/question?id=21296665
http://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
http://discuss.leetcode.com/questions/148/construct-binary-tree-from-preorder-and-inorder-traversal
No comments:
Post a Comment