我遇到了一个真正让我感兴趣的问题,但我不确定自己完全理解如何完成手头的任务:设计一个算法来构造二叉树两个n长序列,已知是相同二叉树的有序和后序遍历的输出。从有序和后序遍历构造二叉树
到目前为止我已经完成了很多工作。下面是我的(相关)代码,但是我也希望能够识别没有二叉树存在的序列。我不知道如何检查这一点。有人能给我一个正确的方向吗?
node* build_tree(int in[], int inStart, int inEnd,
int post[], int postStart, int postEnd) {
if(inStart > inEnd || postStart > postEnd)
return NULL;
int rootValue = post[postEnd];
node *tNode = new_node(rootValue);
// find the index of this node in in-order traversal
int inIndex = search(in, inStart, inEnd, rootValue);
// Using index in in-order traversal, construct left and right subtrees
tNode->left = build_tree(in, inStart, inIndex-1, post, postStart, postStart+inIndex-(inStart+1));
tNode->right = build_tree(in, inIndex+1, inEnd, post, postStart + inIndex - inStart, postEnd - 1);
return tNode;
}
// Function to find index of value in arr[start...end]
// The function assumes that value is present in in[]
int search(int arr[], int start, int end, int value) {
int i;
for(i = start; i < end; i++) {
if(arr[i] == value)
return i;
}
return i;
}
// function that allocates a new node with the
// given data and NULL left and right pointers
node* new_node(int data) {
node* n = (node*)malloc(sizeof(node));
n->data = data;
n->left = NULL;
n->right = NULL;
return n;
}
你的问题的说明是好的。因此,请注意算法,以便我们可以批评您的方法。如果你不这样做,你会被低估和/或关闭。 – Gene 2014-11-04 00:45:40
我添加了我的代码到目前为止,我认为它很接近。我只是不知道如何验证输出并证明它正在工作。 – user3270760 2014-11-04 01:00:50
只需遍历树中你要产生的顺序和后序,并将它们与输入进行比较! – Gene 2014-11-04 02:09:01