使用 c++ 在二叉树中非递归添加函数
我正在编写一个 Add 函数以非递归方式向二叉树添加节点。 我遇到了只能生成一层深二叉树的问题。我调试了它,我知道问题出在哪里,但不知道如何修复它。也许新的眼睛会看到一些我看不到的东西...... 问题是我的临时节点在每次新函数调用时都会重置为根值,因此会线性添加节点。 无论如何,这是功能:
void BinaryTreeNonRec::add(int num){
treeNode *temp, *parent;
if (root==NULL) {
root = new treeNode;
root->data=num;
root->left=0;
root->right=0;
temp=root;
printf("value is root \n");
} else {
temp=root;
while (temp!=NULL) {
if (num <= temp->data){
parent = temp;
temp=temp->left;
//root =temp;
printf("value is to the left \n");
} else {
parent =temp;
temp=temp->right;
//root=temp;
printf("value is to the right \n");
}
}
parent = new treeNode;
parent->data=num;
parent->left=NULL;
parent->right=NULL;
temp=parent;
}
}
感谢您的任何帮助。
I am writing an Add function to add nodes to a binary tree non recursively.
I have run into the problem of only being able to produce one level deep binary tree. I debugged it and I know where the problem is but can't figure out how to fix it. Maybe fresh pair of eyes will see something i dont...
The problem is that my temp node is being reset to the root value every new function call and hence, adding nodes linearly.
Anyways, here is the function:
void BinaryTreeNonRec::add(int num){
treeNode *temp, *parent;
if (root==NULL) {
root = new treeNode;
root->data=num;
root->left=0;
root->right=0;
temp=root;
printf("value is root \n");
} else {
temp=root;
while (temp!=NULL) {
if (num <= temp->data){
parent = temp;
temp=temp->left;
//root =temp;
printf("value is to the left \n");
} else {
parent =temp;
temp=temp->right;
//root=temp;
printf("value is to the right \n");
}
}
parent = new treeNode;
parent->data=num;
parent->left=NULL;
parent->right=NULL;
temp=parent;
}
}
Thanks for any kind of help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不是将新节点添加到树中,只是沿着树向下运行并用新节点填充父节点,但从不将其添加到树中,请将以下代码更改
为:
You are not adding the new node to the tree, just running down the tree and filling parent with a new node, but never adding it to the tree, change below code:
To:
问题可能是您从未将新节点添加到树中。
您将新节点分配给 temp 和parent,它们是临时变量,因此不存在于函数外部。您要做的是将新节点分配给父级>左节点或父级>右节点,具体取决于您的新输入位于哪一侧,以便将其链接到树中。因此,您想要做的是如下所示:
The problem might be that you never add your new node to the tree.
You assign your new node to temp and parent, which are temporary variables and therefore don't exist outside of the function. What you have to do is assign your new node to either parent->left or parent->right, depending on which side your new input lies, in order to link it into the the tree. Therefore what you want to do is something like the following:
算法
代码
Algo
Code