// PreOrder A B C D E F
// InOrder C B D A E F
// Build Tree
public static Node GetTree(char[] PreOrder, char[] InOrder, int index = 0)
{
Node root = new Node();
root.data = PreOrder[index];
int inIndex = Array.IndexOf(InOrder, PreOrder[index]);
if ( index + 1 < PreOrder.Length && IsLeftSubtree(PreOrder[index + 1], InOrder, inIndex) == true)
root.left = GetTree(PreOrder, InOrder, index + 1);
else
root.left = null;
if (inIndex + 1 < InOrder.Length && IsPredecessor(InOrder[inIndex + 1], PreOrder, index) == false)
root.right = GetTree(PreOrder, InOrder, inIndex + 1);
else
root.right = null;
return root;
}
private static bool IsPredecessor(char c, char[] PreOrder, int index)
{
return Array.IndexOf(PreOrder, c) < index;
}
private static bool IsLeftSubtree(char c, char[] InOrder, int index)
{
return Array.IndexOf(InOrder, c) < index;
}
// InOrder C B D A E F
// Build Tree
public static Node GetTree(char[] PreOrder, char[] InOrder, int index = 0)
{
Node root = new Node();
root.data = PreOrder[index];
int inIndex = Array.IndexOf(InOrder, PreOrder[index]);
if ( index + 1 < PreOrder.Length && IsLeftSubtree(PreOrder[index + 1], InOrder, inIndex) == true)
root.left = GetTree(PreOrder, InOrder, index + 1);
else
root.left = null;
if (inIndex + 1 < InOrder.Length && IsPredecessor(InOrder[inIndex + 1], PreOrder, index) == false)
root.right = GetTree(PreOrder, InOrder, inIndex + 1);
else
root.right = null;
return root;
}
private static bool IsPredecessor(char c, char[] PreOrder, int index)
{
return Array.IndexOf(PreOrder, c) < index;
}
private static bool IsLeftSubtree(char c, char[] InOrder, int index)
{
return Array.IndexOf(InOrder, c) < index;
}
No comments:
Post a Comment