标准二叉搜索树的代码不包含任何信息,只包含节点的值。有什么方法可以在节点中包含另一个值,例如年龄?因此节点编号将是id而它所携带的值将是年龄。基本上每个节点都包含一个键值对。谢谢您的帮助!
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
struct node
{
int key;
struct node *left, *right;
};
//to create a new BST node
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d \n", root->key);
inorder(root->right);
}
}
//function to insert a new node with given key in BST
struct node* initialize(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
node->left = initialize(node->left, key);
else if (key > node->key)
node->right = initialize(node->right, key);
/* return the node pointer */
return node;
}
struct node* insert(node* root, int key)
{
// Create a new Node containing
// the new element
node* newnode = newNode(key);
// Pointer to start traversing from root and
// traverses downward path to search
// where the new node to be inserted
node* x = root;
// Pointer y maintains the trailing
// pointer of x
node* y = NULL;
while (x != NULL) {
y = x;
if (key < x->key)
x = x->left;
else
x = x->right;
}
// If the root is NULL i.e the tree is empty
// The new node is the root node
if (y == NULL) {
y = newnode;
}
// If the new key is less then the leaf node key
// Assign the new node to be its left child
else if (key < y->key){
y->left = newnode;
}
// else assign the new node its right child
else{
y->right = newnode;
}
// Returns the pointer where the
// new node is inserted
return y;
}