从堆栈创建二叉树?

发布于 2024-10-01 19:59:44 字数 759 浏览 0 评论 0原文

我的任务是创建一个程序,将 ((X+3)*(X+4)) 之类的东西转换为二叉树,并具有一些其他功能。到目前为止,我已经接受了输入,并将其解析为两个堆栈,一个包含操作数,另一个包含运算符。

我现在只是简单地定义了堆栈(因此它们只有一个 nextnode 和 char 值。 但是,我似乎在将堆栈中的值添加到树中时遇到问题(因此可能是定义树时出现问题)。

我的堆栈定义如下:

typedef struct node
{
    char value;
    struct node * nextnode;
} node;

我的树定义:

typedef struct tree
{
    node * thisNode;
    struct tree *right, *left;
} tree;

我不确定节点*部分,也许它应该有所不同。

对于初学者来说,我一直在考虑 2+3 的简单情况。在这种情况下,树的根应该是+,左边是2,右边是3。

 +
/\
2 3

如何将堆栈上的东西添加到我的树中?我尝试过使用

root->thisNode = operatorTop;

其中operatorTop是操作符堆栈的顶部(定义为node *operatorTop), 但即使是这条简单的线似乎也存在段错误。

I'm tasked with creating a program that turns something like ((X+3)*(X+4)) into a binary tree, along with some other features. So far, I have taken in the input, and parsed it into two stacks, one containing the operands, the other the operators.

I defined the stacks simply for now (so they only have a nextnode and char value.
However, I seem to have problems adding values from the stacks into my tree (so probably a problem in defining the tree).

My stack is defined as such:

typedef struct node
{
    char value;
    struct node * nextnode;
} node;

My tree is defined:

typedef struct tree
{
    node * thisNode;
    struct tree *right, *left;
} tree;

I'm not sure about the node* part, perhaps it should be something different.

I've been considering the simple case of 2+3 for starters. In this case, the root of the tree should be +, with left being 2 and right being 3.

 +
/\
2 3

How to add something that's on a stack to my tree? I have tried using

root->thisNode = operatorTop;

Where operatorTop is the top of the operator stack (defined as node * operatorTop),
but even that simple line seems to segfault.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

娇柔作态 2024-10-08 19:59:44

也许问题是您没有调用malloc()来为root保留空间。

(编译器将报告空指针分配,但在空点取消引用时会出现段错误,因为您指向随机位置。)

Maybe the problem is you have not called malloc() to reserve the space for root.

(Compilers will report null pointer assignment, but segfault on null point dereference because you are pointing to a random place.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文