在this链接之后,我修改了代码以根据后序和顺序遍历构建二叉树。但输出似乎产生了一些垃圾值。我无法理解我哪里出错了。前序遍历在开头有根,后序遍历在结尾有根。使用该逻辑,我修改了代码。如下:
struct tree* buildTree2(char in[], char post[], int inStrt, int inEnd)
{
static int postIndex = sizeof(post)/sizeof(post[0]) - 1; //postorder index
if(inStrt > inEnd)
return NULL;
struct tree* tNode = newNode(post[postIndex--]);
if(inStrt == inEnd)
return tNode;
else
{
int inIndex = search(in, inStrt, inEnd, tNode->data);
tNode->left = buildTree(in, post, inStrt, inIndex-1);
tNode->right = buildTree(in, post, inIndex+1, inEnd);
return tNode;
}
}
输出:
The inorder traversal of the build tree (using preorder traversal) is : D B E A F C
The inorder traversal of the build tree (using postorder traversal) is : D B I R O 7 = R N T V _ G D X t u o . a / .
修改后的代码:
struct tree* buildTree2(char in[], char post[], int inStrt, int inEnd, int postIndex)
{
//printf("\n %d ",postIndex);
if(inStrt > inEnd) //termination condition for buildTree(in, post, inIndex+1, inEnd)
return NULL;
struct tree* tNode = newNode(post[postIndex--]);
//check if node has children
if(inStrt == inEnd)
return tNode;
else
{
//get the index of the postorder variable in the inorder traversal
int inIndex = search(in, inStrt, inEnd, tNode->data);
//Recursively build the tree
tNode->left = buildTree2(in, post, inStrt, inIndex-1, postIndex);
//The inIndex value points to the tNode. So less than that is left sub tree and more than that is the right sub tree
tNode->right = buildTree2(in, post, inIndex+1, inEnd, postIndex);
return tNode;
}
}
输出:
The inorder traversal of the build tree (using preorder traversal) is : D B E A F C
The inorder traversal of the build tree (using postorder traversal) is : E B E