二叉排序树 北邮 机试 静态实现

本文介绍了一个使用C++实现的二叉树插入操作方法。通过静态数组实现二叉树节点存储,利用递归方式完成节点的插入,并在插入新节点的同时输出其父节点的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
//二叉树的静态实现 
struct node{
    int l,r,data;
}Node[105];
int inde=0;
int newnode(int x){
	Node[inde].l=Node[inde].r=-1;
	Node[inde].data=x;
	return inde++;
 } 
 void insert(int &root,int x)//注意引用符 
 {
 	if(root==-1){
 		root=newnode(x);
 		return;
	 }
	 if(x<Node[root].data){
	 	if(Node[root].l==-1) cout<<Node[root].data<<endl;
	 	insert(Node[root].l,x);
	 }
	 else{//注意左右 
	 	if(Node[root].r==-1) cout<<Node[root].data<<endl;
	 	insert(Node[root].r,x);
	 }
 }
int main()
{
	int n,x;
	cin>>n;
	cout<<-1<<endl;//输出根节点 
	int rooot=-1;//永远的根节点,根节点设为-1才能跟insert函数匹配 
	for(int i=0;i<n;i++){
		cin>>x;//节点表是从0开始 
		insert(rooot,x);//在插入时输出父节点的值  
//******必须要用 rooot而不能用-1,因为insert函数中引用root,传的是地址不是数值 
	}	
	return 0;
 } 

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值