//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'变量。我没有真正看到如何在不使用局部变量或更改指向根的指针的情况下执行此操作。
答案 0 :(得分:1)
您的插入例程只会将一个节点插入根目录。
if(!itr)
{
itr = new_node;
break;
}
由于itr
是一个局部变量,new_node
实际上并未插入。你可以通过使itr
指向像root这样的指针来纠正这个问题。
node **itr = root;
while(1)
{
if((*itr)->value > new_node->value)
itr = &(*itr)->left;
else
itr = &(*itr)->right;
if(!*itr)
{
*itr = new_node;
break;
}
}
答案 1 :(得分:1)
使用std :: set。你的代码似乎是旧的C代码。是C ++:
#include <set>
#include <iostream>
int main()
{
std::set<int> binary_tree;
binary_tree.insert(5);
binary_tree.insert(10);
binary_tree.insert(3);
binary_tree.insert(1);
binary_tree.insert(4);
//inorder_print(binary_tree);
for (std::set<int> i = binary_tree.begin(); i != binary_tree.end(); ++i)
std::cout << *i << std::endl;
}