【发布时间】:2022-02-27 02:47:00
【问题描述】:
在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
【问题讨论】:
-
sizeof(post)/sizeof(post[0])。这并不像您认为的那样(打印并查看)。 C 不是 Java(只是一个友好的提醒)。 -
我尝试对输入(数组中的最后一个索引)进行硬编码,但它仍然不起作用@n.m.
-
修复第一个bug,然后我们可以专注于下一个。
-
@n.m.我已经修复了这个错误。但问题还是一样。
-
OK 将 postindex 作为参数比作为静态参数要好得多;)这里的另一个问题是 preorder 和 postorder 不是彼此的镜像。前序是“根、左、右”,后序是“左、右、根”。也就是说,在前序中,在根之后的是左子树,而在后序中,在根之前的是右子树。
标签: c tree binary-tree