Tue. Mar 19th, 2024

Trees – Traversal Post-order

  1. Check if the current node is empty / null
  2. Traverse the left subtree by recursively calling the post-order function.
  3. Traverse the right subtree by recursively calling the post-order function.
  4. Display the data part of the root (or current node).
#define _CRT_SECURE_NO_DEPRECATE	//disable scanf deprecate(?)
#include <stdio.h>


#define MAX 100

//stang[i] - descendentul stang al nodului i: 0 daca nu exista
char stang[MAX];

//drept[i] - descendentul drept al nodului i: 0 daca nu exista
char drept[MAX];

//tata[i] - parintele nodului i
char tata[MAX];

//nr de noduri din arbore
int n;

//nodul radacina din arbore
int rad;

void vizit(int nod)
{
	printf("%2d",nod);
}

void cit_date()
{
	int k;

	printf("Nr.noduri = ");
	scanf("%d",&n);
	printf("Radacina = ");
	scanf("%d",&rad);
	for (k=1;k<=n;k++)
	 {
		printf("stang[%d]= ",k);
		scanf("%d",&stang[k]);
	 }
	for (k=1;k<=n;k++)
	 {
		printf("drept[%d]= ",k);
		scanf("%d",&drept[k]);
	 }
	for (k=1;k<=n;k++)
	 {
		printf("tata[%d]= ",k);
		scanf("%d",&tata[k]);
	 }
}

void preord(int rad)
{
	int i,j;
	int q,q1;

	i = rad;
	q = 0;

	while(q == 0)
	{
		while(stang[i] != 0)
		{
			i = stang[i]; //se viziteaza stanga
			vizit(i); //se viziteaza rdacina
			
		}
		//vizit(i); //se urca spre radacina
		while(drept[i] == 0 && q == 0)
		{
			q1 = 0;
			while(q == 0 && q1 == 0)
			{
				j = i;
				i = tata[i];
				if(i == 0)
					q = 1;
				else
					if(j == stang[i])
						q1 = 1;
			}
		}
		if(q == 0)
			i = drept[i];
	}
}

void main()
{
	cit_date();
	preord(rad);
}

41,789 total views, 1 views today