#include <iostream>
#include <cstdlib>
#include <string>
#include <cstdio>
using namespace std;
struct node{
int key;
node *r,*l,*p;
};
node *root,*NIL;
void insert(int k){
node *x=root;
node *y=NIL;
node *z;
z=(node *)malloc(sizeof(node));
z->key=k;
z->r=NIL;
z->l=NIL;
while (x!=NIL){
y=x;
if (z->key<x->key){
x=x->l;
}else{
x=x->r;
}
}
z->p=y;
if (y==NIL){
root=z;
}else {
if (z->key < y->key) {
y->l = z;
} else {
y->r = z;
}
}
}
void midt(node *u){
if (u==NIL){
return;
}
midt(u->l);
cout<<" "<<u->key;
midt(u->r);
}
void pret(node *u){
if (u==NIL){
return;
}
cout<<" "<<u->key;
midt(u->l);
midt(u->r);
}
int main() {
int n;
int x;
cin>>n;
string s;
for (int i = 0; i < n; ++i) {
cin>>s;
if (s=="insert"){
cin>>x;
insert(x);
}else if (s=="print"){
midt(root);
cout<<endl;
pret(root);
cout<<endl;
}
}
return 0;
}
测试用例
8
insert
30
insert
88
insert
12
insert
1
insert
20
insert
17
insert
25
print
输出
1 12 17 20 25 30 88
30 1 12 17 20 25 88
这里强调一下 ,因为该算法的low 导致无法平衡二叉树,所以在某些特殊情况下,树的高度接近于结点数N
这个原因出现在这里
while (x!=NIL){
y=x;
if (z->key<x->key){
x=x->l;
}else{
x=x->r;
}
}
因为这个while循环只会无脑的找到比当前结点大或者小的子节点
而他忽略了对当前节点父节点与要插入值的判断 如果加入这个判断的话 那么 二叉树就会平衡很多,否则 他在某种数据下 只会单向生长 淦 希望继续努力 加油
下面说一说二叉树的的搜索
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstdio>
using namespace std;
struct node{
int key;
node *r,*l,*p;
};
node *root,*NIL;
void insert(int k){
node *x=root;
node *y=NIL;
node *z;
z=(node *)malloc(sizeof(node));
z->key=k;
z->r=NIL;
z->l=NIL;
while (x!=NIL){
y=x;
if (z->key<x->key){
x=x->l;
}else{
x=x->r;
}
}
z->p=y;
if (y==NIL){
root=z;
}else {
if (z->key < y->key) {
y->l = z;
} else {
y->r = z;
}
}
}
void midt(node *u){
if (u==NIL){
return;
}
midt(u->l);
cout<<" "<<u->key;
midt(u->r);
}
void pret(node *u){
if (u==NIL){
return;
}
cout<<" "<<u->key;
midt(u->l);
midt(u->r);
}
node * find(node * u, int t){
while (u!=NIL&&t!=u->key){
if (t<u->key){
u=u->l;
}else{
u=u->r;
}
}
return u;
}
int main() {
int n;
int x;
cin>>n;
string s;
for (int i = 0; i < n; ++i) {
cin>>s;
if (s=="find"){
cin>>x;
node *t=find(root,x);
if (t!=NIL){
cout<<"yes";
}else{
cout<<"no";
}
}
else if (s=="insert"){
cin>>x;
insert(x);
}else if (s=="print"){
midt(root);
cout<<endl;
pret(root);
cout<<endl;
}
}
return 0;
}
测试用例以及输出
10
insert
30
insert
88
insert
12
find 9
no
insert
20
find 12
yes
insert 17
insert 25
find 16
no
print
12 17 20 25 30 88
30 12 17 20 25 88
然而这个搜索只是多了一个
node * find(node * u, int t){
while (u!=NIL&&t!=u->key){
if (t<u->key){
u=u->l;
}else{
u=u->r;
}
}
return u;
}
这个函数 还是很容易懂的 和学长说的 二叉树的狂搜爆搜 不太一样
革命尚未成功同志还需努力