二叉搜索树-插入 ALDS1_8:Binary Search Tree I

在写这道题的时候犯了一个错误,迷瞪了半天。这里要提醒一下大家。
在题目中有代码如下:

z->key = k; 
z->left=NIL;
z->right=NIL;

这段代码是必要的,不能省略,因为在后面的递归查询的时候,递归的终止条件是
u==NIL

这里给大家分享一个小知识,也是我在做题过程中发现得。
全局指针变量在未赋值前,地址默认为都0。
局部指针变量在未赋值前,地址是任意给定的。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
using namespace std;
int it=0;

struct node{
	int key;
	node *parent, *left, *right;
};

bool fs=false;
node *root, *NIL;

void insert(int k){
	node *z=(node*)malloc(sizeof(node));
	node *x;
	node *y;
	z->key = k;
	z->left=NIL;
	z->right=NIL;
	if(fs==false){
		root = z;
		fs = true;
	}else{
		x = root;
		while(x!=NIL){
			y = x;
			if(z->key< x->key){
				x=x->left;
			}else{
				x=x->right;
			}
		}
		if(y->key<z->key){
			y->right=z;
			z->parent=y;
		}else{
			y->left=z;
			z->parent=y;
		}
	}
}

void print(node *u){
	if(u==NIL) return;
	cout<<u->key<<" ";
	print(u->left);
	print(u->right);
}

void opt(node *u){
	if(u==NIL) return;
	opt(u->left);
	cout<<u->key<<" ";
	opt(u->right);
}

int main(){
	int n, num;
	string str;
	cin>>n;
	for(int i=0; i<n; i++){
		cin>>str;
		if(str=="insert"){
			cin>>num;
			insert(num);
		}else if(str=="input"){
			print(root);
			opt(root);
		}
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值