我试图为练习实现一个简单的二进制搜索树。我试图只添加值并在节点中打印值。但是,我没有在节点中获得正确的值升序。这就是我所拥有的:
struct Node
{
int data;
Node* leftN;
Node* rightN;
};
typedef Node* Node_ptr;
Node_ptr head;
//INSERT_VALUE FUNCTION
Node* insert_value(Node_ptr leaf, int key)
{
//Root case when there is no set value yet
if(leaf == NULL)
{
leaf = new Node;
head = leaf;
cout << "Make the first node" << endl;
leaf->data = key;
leaf->leftN = NULL;
leaf->rightN = NULL;
return leaf;
}
//Left child Node
if(key < leaf->data)
{
//Search for a spot in the tree to add a Node (left value < root value < right value)
//This is only true for the left child Node
if(leaf->leftN != NULL)
insert_value(leaf, key);
//We have found a spot in the tree to add a new Node and add the value of key
else
{
cout << "Insert-left" << endl;
leaf->leftN = new Node;
leaf = leaf->leftN;
leaf->data = key;
leaf->leftN = NULL;
leaf->rightN = NULL;
return leaf;
}
}
//Right child Node
else if(key >= leaf->data)
{
//Search for a spot to add a new Node in the tree (only amongst the right child Nodes)
if(leaf->rightN != NULL)
insert_value(leaf, key);
//Once we have found a spot to add a new Node, append the new Node
else
{
cout << "Insert-right" << endl;
leaf->rightN = new Node;
leaf = leaf->rightN;
leaf->data = key;
leaf->leftN = NULL;
leaf->rightN = NULL;
return leaf;
}
}
}
//PRINT FUNCTION
void printTree(Node_ptr leaf)
{
if(leaf == NULL)
return;
printTree(leaf->leftN);
cout << "Data element: " << leaf->data << endl;
printTree(leaf->rightN);
}
//MAIN
int main()
{
Node_ptr root = NULL;
int i;
//initialize values
for(i = 1; i < 12; i+=2)
root = insert_value(root, i);
root = head;
for(i = 0; i < 11; i+=2)
root = insert_value(root, i);
root = head;
printTree(root);
root = head;
cout << "Head Node: " << root->data << endl;
return 0;
}
当我打印结果时,这就是我得到的: 0,2,4,6,8,10,1,3,5,7,9,11和头节点的值是1
答案 0 :(得分:1)
因为您将插入称为:
root = insert_value(root, i);
您插入的位置始终使用从上次插入开始的子树。除了重新开始添加奇数的时间,当你开始插入头部时。
如果你创建一个包含头指针的class BinarySearchTree
,以及一个调用int value
的{{1}}的insert方法,那么你可以只调用该类的insert,而不传递它一个节点,它总是可以看到插入使用树的根来开始递归。
只是我,但我会为Node创建一个构造函数,它接受Node::insert( head, value )
并将指针初始化为NULL。这样你就不必在insert方法中这样做了。
答案 1 :(得分:0)
在leaf-&gt;节点? != NULL情况,我认为不是调用
insert_value(leaf, key);
你想说
leaf->node? = insert_value(leaf->node?, key)
在哪里?当然是L或R.
您可能会考虑的是向方法添加注释,如下所示:
// Adds the given key to the (sub-)tree rooted at node* then returns the new root
// of that (sub-)tree.
node *insert_value_and_return_root(node *root, int value) { ... }