[Data structure] Tree expression

//The code of this article is the first edition code of P153 of "Challenge Programming Competition 2" + comments you understand

Brief description of the topic: print tree information

Input: Enter n in the first line to indicate the number of points, then enter the node information (id k c_{1} c_{2}... c_{k}) for each line in the next n lines

Output: output node information according to the format (format is omitted)

Code:

 

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<iomanip>
#include <stdlib.h>  
using namespace std;
#define MAX 100005
#define NIL -1

struct Node{
	int p,l,r;
};//利用“左子右兄弟表示法”记录每个节点的信息 

Node T[MAX];
int n,D[MAX];

//打印相关信息 
void print(int u){
	int i,c;
	cout<<"node "<<u<<": ";
	cout<<"parent= "<<T[u].p<<' ';
	cout<<"depth= "<<D[u]<<' ';
	
	if(T[u].p==NIL) cout<<"root";
	else if(T[u].l==NIL) cout<<"leaf";
	else cout<<"internal node";
	
	
	cout<<'[';
	for(i=0,c=T[u].l;c!=NIL;i++,c=T[c].r){
		if(i)cout<<',';//排版 
		cout<<c;//输出子节点的序号 
	}
	cout<<']';
}

//递归求深度
int rec(int u,int p){
	D[u]=p;//记录深度 
	if(T[u].r!=NIL)rec(T[u].r,p);//右兄弟和自己的深度相同 
	if(T[u].l!=NIL)rec(T[u].l,p+1);//左子是自己深度+1 
}
int main(){
	int i,j,d,v,c,l,r;
	cin>>n;
	for(int i=0;i<n;i++)T[i].p=T[i].l=T[i].r=NIL;//初始化 
	
	for(int i=0;i<n;i++){
		cin>>v>>d;
		for(int j=0;j<d;j++){
			cin>>c;
			
			if(j==0)T[v].l=c;
			else T[l].r=c;
			
			l=c; //这里比较巧妙地表述了兄弟节点( 
			T[c].p=v;//记录父节点
		}
	}
	
	for(i=0;i<n;i++) if(T[i].p==NIL) r=i;//遍历,寻找根
	
	rec(r,0);//从根开始利用递归记录各个节点深度 
	
	for(i=0;i<n;i++)print(i);//打印所有节点的信息 
	return 0;
}

 

Guess you like

Origin blog.csdn.net/melon_sama/article/details/108546457