使用C ++的二叉树中的非递归添加函数 [英] Non-recursive add function in a binary tree using c++
问题描述
我正在编写一个Add函数,以非递归方式将节点添加到二叉树中. 我遇到了只能产生一级深度二叉树的问题.我调试了它,我知道问题出在哪里,但不知道如何解决.也许新鲜的眼睛会看到我看不到的东西. 问题是我的临时节点在每次新函数调用时都会重置为根值,因此会线性添加节点. 无论如何,这是函数:
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;
}
}
感谢任何帮助.
推荐答案
您没有将新节点添加到树中,只是沿树运行并用新节点填充父节点,但从未将其添加到树中,请进行更改下面的代码:
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:
parent = new treeNode;
parent->data=num;
parent->left=NULL;
parent->right=NULL;
temp=parent;
收件人:
treeNode *newNode = new treeNode;
newNode->data = num;
newNode->left = NULL;
newNode->right = NULL;
//Now insert the new node BELOW parent
if(num <= parent->data)
parent->left = newNode;
else
parent->right = newNode;
这篇关于使用C ++的二叉树中的非递归添加函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!