How can I get the tree form these pre/in order traversal:
Pre: A,B,D,E,C,F,G,H in:E,D,B,A,G,F,H,C
EDITED: MY Answer
A
Below is a working implementation in C#
public static class TreeUtil
{
public static BinarySearchTree FromTraversals(T[] preorder, T[] inorder)
{
if (preorder == null) throw new ArgumentNullException("preorder");
if (inorder == null) throw new ArgumentNullException("inorder");
if (preorder.Length != inorder.Length) throw new ArgumentException("inorder and preorder have different lengths");
int n = preorder.Length;
return new BinarySearchTree(FromTraversals(preorder, 0, n - 1, inorder, 0, n - 1));
}
public static BinaryTreeNode FromTraversals(T[] preorder, int pstart, int pend, T[] inorder, int istart, int iend)
{
if (pstart > pend) return null;
T rootVal = preorder[pstart];
int rootInPos;
for (rootInPos = istart; rootInPos <= iend; rootInPos++) //find rootVal in inorder
if (Comparer.Default.Compare(inorder[rootInPos], rootVal) == 0) break;
if (rootInPos > iend)
throw new ArgumentException("invalid inorder and preorder inputs");
int offset = rootInPos - istart;
return new BinaryTreeNode(rootVal)
{
Left = FromTraversals(preorder, pstart + 1, pstart + offset, inorder, istart, istart + offset - 1),
Right = FromTraversals(preorder, pstart + offset + 1, pend, inorder, istart + offset + 1, iend),
};
}
}
Here is one possible implementation of BinarySearchTree
[TestMethod]
public void TestGenerationFromTraversals()
{
var preorder = new[] {1, 2, 4, 5, 3};
var inorder = new[] {4, 2, 5, 1, 3};
AssertGenerationFromTraversal(preorder, inorder);
var preorder2 = new[] { 'A', 'B', 'D', 'E', 'C', 'F' };
var inorder2 = new[] { 'D', 'B', 'E', 'A', 'F', 'C' };
AssertGenerationFromTraversal(preorder2, inorder2);
}
private static void AssertGenerationFromTraversal(T[] preorder, T[] inorder)
{
var tree = BinarySearchTreeUtil.FromTraversals(preorder, inorder);
var treeInorder = new List();
tree.TraverseInOrder(treeInorder.Add);
var treePre = new List();
tree.TraversePreOrder(treePre.Add);
Assert.IsTrue(preorder.SequenceEqual(treePre));
Assert.IsTrue(inorder.SequenceEqual(treeInorder));
}