【发布时间】:2016-05-09 14:44:09
【问题描述】:
我有以下代码用于将节点插入树中。问题是代码不起作用,没有编译错误,但输出不正确。代码如下:
#include <stdio.h>
struct node {
int data;
node *left;
node *right;
};
node * insertNode(node *root, int value) {
if(root == NULL) {
printf("%s\n", "root is null, making new node");
node * new_node = new node;
new_node->data = value;
new_node->left = NULL;
new_node->right = NULL;
root = new_node;
printf("%s\n", "root assigned to new node");
}
else {
if(root->data < value) {
printf("%s\n", "Right subtree");
insertNode(root->right, value);
} else {
printf("%s\n", "Left subtree");
insertNode(root->left, value);
}
}
return root;
}
void printTree(node *root) {
if(root != NULL) {
if(root->left != NULL) {
printTree(root->left);
}
printf("%d ", root->data);
if(root->right != NULL) {
printTree(root->right);
}
}
else {
printf("%s\n", "root is null");
return;
}
}
int main()
{
node *root = new node;
root->data = 1;
root->left = NULL;
root->right = NULL;
root = insertNode(root, 2);
printTree(root);
return 0;
}
我哪里错了?
【问题讨论】:
-
您应该使用调试器单步执行您的程序以查找错误源。
-
也许发布运行时错误是什么?仅仅写“没有编译错误,但是运行时错误”并没有提供太多关于你的问题的信息。
-
@rbaleksandar 我的意思是说,在编译过程中我没有遇到任何问题,但在运行时输出不正确。我的错,这是误导。
-
我明白,“输出不正确”只是在拐弯抹角。对于未来,我对您的建议是:以尽可能紧凑的形式提供尽可能多的信息。
-
你为什么不使用std::set?
标签: c++ binary-tree insertion