社区讨论

二叉树基础操作求调

学术版参与者 2已保存回复 3

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
3 条
当前快照
1 份
快照标识符
@lo3d9f25
此快照首次捕获于
2023/10/24 04:44
2 年前
此快照最后确认于
2023/10/24 04:44
2 年前
查看原帖
Rt,第一次用指针和引用写链式存储。
CPP
#include<bits/stdc++.h>
using namespace std;
struct node{
	node *left,*right,*parent;
	int lr,value,depth,degree,script;
	bool isroot,isleaf;
};
node tr[1001];
int nodenum,qaq,qwq,root;
void pretra(node nod){
	cout<<nod.script<<":"<<nod.value<<' ';
	pretra(nod.left);
	pretra(nod.right);
}
void midtra(node nod){
	midtra(nod.left);
	cout<<nod.script<<":"<<nod.value<<' ';
	midtra(nod.right);
}
void postra(node nod){
	postra(nod.left);
	postra(nod.right);
	cout<<nod.script<<":"<<nod.value<<' ';
}
void getdepth(node &nod,int depth){
	nod.depth=depth;
	getdepth(nod.left,depth+1);
	getdepth(nod.right,depth+1);
}
void getlr(node &nod,int lr){
	nod.lr=lr;
	getdepth(nod.left,lr-1);
	getdepth(nod.right,lr+1);
}
int main(){
	//build
	cin>>nodenum;
	for(int i=0;i<nodenum;i++){
		cin>>tr[i].value>>qaq>>qwq;
		tr[i].script=i;
		if(qaq==-1&&qwq==-1){
			tr[i].isleaf=1;
			tr[i].degree=0;
			tr[i].left=NULL;
			tr[i].right=NULL;
		}else if(qaq==-1){
			tr[i].degree=1;
			tr[i].left=NULL;
			tr[i].right=tr[qwq];
			tr[qwq].parent=tr[i];
		}else if(qwq==-1){
			tr[i].degree=1;
			tr[i].right=NULL;
			tr[i].left=tr[qaq];
			tr[qaq].parent=tr[i];
		}else{
			tr[i].degree=2;
			tr[i].left=tr[qaq];
			tr[i].right=tr[qwq];
			tr[qaq].parent=tr[i];
			tr[qwq].parent=tr[i];
		}
	}
	//findroot
	for(int i=0;i<nodenum;i++){
		if(tr[i].parent==NULL){
			tr[i].isroot=1;
			root=i;
		}
		else tr[i].isroot=0;
	}
	//getdepth&lr
	getdepth(tr[root],1);
	getlr(tr[root],0);
	//traverasl
	pretra(tr[root]);
	cout<<"\n\n";
	midtra(tr[root]);
	cout<<"\n\n";
	postra(tr[root]);
}
验证码xrmj(闲人免进)

回复

3 条回复,欢迎继续交流。

正在加载回复...