c 언어는 두 갈래 트리와 앞뒤 순서를 반복한다

1844 단어
c 언어는 두 갈래 트리와 앞뒤 순서를 반복한다(반복 반복 방식을 사용한다)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
// 
typedef struct BTNode{
	char data;
	struct BTNode *rchild,*lchild;
}BTNode,*BTtree;

BTtree createBTNode(BTtree ptr, char value, char child){
	// 
	BTtree ptemp = (BTtree)malloc(sizeof(BTNode));
	if(NULL == ptemp){
		puts(" !");
		exit(1);
	}
	ptemp->data = value;
	ptemp->rchild = NULL;
	ptemp->lchild = NULL;
	if(child == 'R'){
		ptr->rchild = ptemp;
	}else if(child == 'L'){
		ptr->lchild = ptemp;
	}
	return ptemp;

}

BTtree initBTree(){
	// 
	BTtree root = (BTtree)malloc(sizeof(BTNode));
	if(root == NULL){
		puts(" ");
		exit(1);
	}
	root->data = 'A';
	root->rchild = NULL;
	root->lchild = NULL;
	BTtree pb = createBTNode(root,'B','L');
	BTtree pc = createBTNode(root,'C','R');
	BTtree pd = createBTNode(pb,'D','L');
	BTtree pe = createBTNode(pb,'E','R');
	BTtree pf = createBTNode(pc,'F','L');
	BTtree pg = createBTNode(pc,'G','R');
	return root;
}
// 

void preorder(BTtree p){
	if(p != NULL){
		printf("%c ",p->data);
		preorder(p->lchild);    // 
		preorder(p->rchild);	// 
	}
}
void inorder(BTtree p){
	if(p != NULL){
		inorder(p->lchild);
		printf("%c ",p->data);
		inorder(p->rchild);
	}
}
void postorder(BTtree p){
	if(p != NULL){
		postorder(p->lchild);
		postorder(p->rchild);
		printf("%c ",p->data);
	}
}
int main(){
	BTtree btroot = initBTree();
	//printf("%c
",btroot->data); printf(" :
"); preorder(btroot); printf("
:
"); inorder(btroot); printf("
:
"); postorder(btroot); return 0; }

좋은 웹페이지 즐겨찾기