C + + Tree-parent representation, child representation, parent-child representation __c++

Source: Internet
Author: User

Parent Representations:

#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;
}


Child representation:


#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;
}

Parent-Child representation:


#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;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.