我正在编写一个 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;
}
}
感谢您提供任何帮助。