struct node{
int key;
node *parent,*left,*right;
};
二叉搜索树的结点
Insert以根为起点寻找结点z在该插入的位置。设当前结点为x,如果z的键值小于x则将当前结点的左子结点作为下一个结点,反之则以右子节点作为下一个x,如此不断向叶节点搜索。在此过程中,程序将前一个结点保存在y里,用作z的候选父节点。当x抵达NIL时搜索结束,此时的y就是z的父节点了。
如果搜索结束时y仍为初始值NIL,就代表插入前的二叉树为空,z即成为根节点。如果插入前的二叉树不为空,那么插入的结点z将跟据键值成为y的左子节点或右子节点。
#include<iostream>
#include<cstdio>
#include<string>
#include<cstdlib>
using namespace std;
struct node{
int key;
node *right,*left,*parent;
};
node *root,*NIL;
void insert(int k)
{
node *y=NIL;
node *x=root;
node *z;
z=(node*)malloc(sizeof(node));
z->key=k;
z->left=NULL;
z->right=NULL;
while(x!=NULL){
y=x;
if(z->key<x->key){
x=x->left;
}else{
x=x->right;
}
}
z->parent=y;
if(y==NIL){
root=z;
}else{
if(z->key<y->key){
y->left=z;
}else{
y->right=z;
}
}
}
void inorder(node *u)
{
if(u==NULL){
return ;
}
inorder(u->left);
printf(" %d",u->key);
inorder(u->right);
}
void preorder(node *u)
{
if(u==NULL){
return ;
}
printf(" %d",u->key);
preorder(u->left);
preorder(u->right);
}
int main()
{
int n,k;
string com;
scanf("%d",&n);
for(int i=0;i<n;i++){
cin>>com;
if(com=="insert"){
scanf("%d",&k);
insert(k);
}else if(com=="print"){
inorder(root);
printf("\n");
preorder(root);
printf("\n");
}
}
return 0;
}
/*
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print
*/