#include<iostream>
#include<stdlib.h>
using namespace std;
struct node{
int data;
struct node *left;
struct node *right;
};
struct tree{
node *root;
};
void insert(tree *name,int data2)//
{
node *p = new node;
p->data = data2;
p->left = NULL;
p->right = NULL;
if(name->root == NULL)//根节为空的情况下,直接将新节点当做树的根
{
name->root = p;
}
else
{
node *q = name->root;
while(q!=NULL)
{
if(data2<q->data)
{
if(q->left==NULL)
{
q->left = p;return;
}
else
{
q = q->left;
}
}
else{
if(q->right==NULL)
{
q->right = p;return;
}
else
{
q=q->right;
}
}
}
}
}
void headfound(node *p)//对树的先序遍历
{
if(p!=NULL)
{
cout<<p->data<<endl;
headfound(p->left);
headfound(p->right);
}
}
void midfound(node *p)//对树的中序遍历
{
if(p!=NULL)
{
midfound(p->left);
cout<<p->data<<endl;
midfound(p->right);
}
}
void endfound(node *p)//对树的后序遍历
{
if(p!=NULL)
{
endfound(p->left);
endfound(p->right);
cout<<p->data<<endl;
}
}
int main()
{
int data[9] = {2,8,9,3,4,6,1,5,7};
tree p;
p.root = NULL;
for(int i = 0;i<9;i++)
{
insert(&p,data[i]);
}
headfound(p.root);
return 0;
}
二叉搜索树
最新推荐文章于 2024-09-14 15:47:59 发布