C++ 树-双亲表示法、孩子表示法、双亲孩子表示法

双亲表示法:

#include<iostream>
using namespace std;
template<typename T>
struct Node{
	T _data;
	int parent;
};
template<typename T>
struct Tree{
	Node<T> array[100];
	int count;
};
template<typename T>
void addNode(T data,int parent,Tree<T>& tree){
	tree.array[tree.count]._data=data;
	tree.array[tree.count].parent=parent;
	tree.count++;
}

int main(){
	
	Tree<int> tree;
	tree.count=0;
	addNode(0,-1,tree);

	for(int i=0;i<tree.count;i++){
		cout<<tree.array[i]._data<<' '<<tree.array[i].parent<<endl;
	}
	return 0;
}


孩子表示法:


#include<iostream>
using namespace std;
struct Child{
	int index;
	Child* next;
};
struct Node{
	int data;
	Child* child;
};
struct Tree{
	Node array[100];
	int count;
};

void AddNode(Tree& t,int data,int parent){
	t.array[t.count].data=data;
	t.array[t.count].child=0;
	if(parent>-1){
		Child* ch=new Child;
		ch->index=t.count;
		ch->next=0;
		Child*& temp=t.array[parent].child;
		while(temp!=0){
			temp=temp->next;
		}
		temp=ch;
	}
	t.count++;
}

int main(){
	Tree tree;
	tree.count=0;
	AddNode(tree,0,-1);
	
	
	for(int i=0;i<tree.count;i++){
		cout<<tree.array[i].data<<endl;
	}
	return 0;
}

双亲孩子表示法:


#include<iostream>
using namespace std;
struct Child{
	int index;
	Child* next;
};
struct Node{
	int data;
	int parent; 
	Child* child;
};
struct Tree{
	Node array[100];
	int count;
};

void AddNode(Tree& t,int data,int parent){
	t.array[t.count].data=data;
	t.array[t.count].child=0;
	t.array[t.count].parent=parent;
	if(parent>-1){
		Child* ch=new Child;
		ch->index=t.count;
		ch->next=0;
		Child*& temp=t.array[parent].child;
		while(temp!=0){
			temp=temp->next;
		}
		temp=ch;
	}
	t.count++;
}

int main(){
	Tree tree;
	tree.count=0;
	AddNode(tree,0,-1);

	
	for(int i=0;i<tree.count;i++){
		cout<<tree.array[i].data<<endl;
	}
	return 0;
}


  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值