当前位置:网站首页>6-3 non recursive traversal of binary tree

6-3 non recursive traversal of binary tree

2022-06-22 21:55:00 White -

6-3 Non recursive traversal of binary trees

This problem requires a non recursive method to achieve a given binary tree 3 Kind of traversal .

Function interface definition :
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
among BinTree The structure is defined as follows :

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
int flag;
};
requirement 3 Each function prints out the content of the node in the order of access , The format is a space followed by a character .

Besides , A complete set of stack operations is given in the referee program , Can be called directly .

Sample referee test procedure :
#include <stdio.h>
#include <stdlib.h>
typedef enum { false, true } bool;

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
int flag;
};

/------ The definition of the stack -------/
typedef Position SElementType;
typedef struct SNode *PtrToSNode;
struct SNode {
SElementType Data;
PtrToSNode Next;
};
typedef PtrToSNode Stack;

/* The referee realizes , Details don't show /
Stack CreateStack();
bool IsEmpty( Stack S );
bool Push( Stack S, SElementType X );
SElementType Pop( Stack S ); /
Delete and return only S Top element of /
SElementType Peek( Stack S );/
Return only S Top element of /
/
---- End of stack definition -----*/

BinTree CreateBinTree(); /* The referee realizes , Details don't show */
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );

int main()
{
BinTree BT = CreateBinTree();
printf(“Inorder:”); InorderTraversal(BT); printf(“\n”);
printf(“Preorder:”); PreorderTraversal(BT); printf(“\n”);
printf(“Postorder:”); PostorderTraversal(BT); printf(“\n”);
return 0;
}
/* Your code will be embedded here */
sample input :
Pictured
 Insert picture description here
sample output :
Inorder: D B E F A G H C I
Preorder: A B D F E C G H I
Postorder: D E F B H G I C A

Code :

void InorderTraversal( BinTree BT ){
    
	if(BT==NULL)
		return ;
	InorderTraversal(BT->Left);
	printf(" %c",BT->Data);
	InorderTraversal(BT->Right);
}
void PreorderTraversal( BinTree BT ){
    
	if(BT==NULL)
		return ;
printf(" %c",BT->Data);
	PreorderTraversal(BT->Left);
	PreorderTraversal(BT->Right);
}
void PostorderTraversal( BinTree BT ){
    
	
	if(BT==NULL)
		return ;
PostorderTraversal(BT->Left);
	PostorderTraversal(BT->Right);
	printf(" %c",BT->Data);
}

202206201635 One

原网站

版权声明
本文为[White -]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222023313759.html