//binary_tree.h file
typedef struct node node;
struct node
{ node():left(0), right(0), value(-1){};
~node(){if(left) delete left; if(right) delete right;};
node *left;
node *right;
int value;
};
inline void insert_node(node **root, node *new_node)
{
assert(new_node != NULL);
if(*root == NULL)
{
*root = new_node;
}
else
{
node *itr = *root;
while(1)
{
if(itr->value > new_node->value)
itr = itr->left;
else
itr = itr->right;
if(!itr)
{
itr = new_node;
break;
}
}
}
}
inline void inorder_print(node *root)
{
if(!root) return;
inorder_print(root->left);
printf("%d\n", root->value);
inorder_print(root->right);
}
//main.cpp file
#include "binary_tree.h"
int main()
{
node *node1 = new node();
node *node2 = new node();
node *node3 = new node();
node *node4 = new node();
node *node5 = new node();
node1->value = 5;
node2->value = 10;
node3->value = 3;
node4->value = 1;
node5->value = 4;
node *binary_tree = NULL;
insert_node(&binary_tree, node1);
insert_node(&binary_tree, node2);
insert_node(&binary_tree, node3);
insert_node(&binary_tree, node4);
insert_node(&binary_tree, node5);
assert(binary_tree != NULL);
inorder_print(binary_tree);
return 0;
}
我有一个非常简单的程序,我想创建一个二叉树并打印它。然而,下面显示的代码段不会改变树结构。
node *itr = *root;
while(1)
{
if(itr->value > new_node->value)
itr = itr->left;
else
itr = itr->right;
if(!itr)
{
itr = new_node;
break;
}
}
inorder_print 函数总是打印 '5'
问题是使用“itr”变量。我真的不明白如何在不使用局部变量或更改指向根的指针的情况下做到这一点。