【数据结构】二叉树的遍历

初始为满二叉树ABCDEFG
先中后序的代码实现

【数据结构】二叉树的遍历

#include <cstdio>
#include <cstdlib>

typedef struct Node{
	char data;
	Node *lchild, *rchild;
}Node, *BiTree;

BiTree newNode(char v){
	BiTree node = (BiTree)malloc(sizeof(BiTree));
	node->data = v;
	node->lchild = NULL;
	node->rchild = NULL;
	return node;
}

void preorder(BiTree T){
	if(T == NULL) return;
	printf("%c", T->data);
	preorder(T->lchild);
	preorder(T->rchild);
}

void inorder(BiTree T){
	if(T == NULL) return;
	inorder(T->lchild);
	printf("%c", T->data);
	inorder(T->rchild);
}

void postorder(BiTree T){
	if(T == NULL) return;
	postorder(T->lchild);
	postorder(T->rchild);
	printf("%c", T->data);
}

int main(){
	BiTree T;
	T = newNode('A');
	T->lchild = newNode('B'), T->rchild = newNode('C');
	T->lchild->lchild = newNode('D'), T->lchild->rchild = newNode('E'), T->rchild->lchild = newNode('F'), T->rchild->rchild = newNode('G');
	printf("先序遍历:");
	preorder(T);
	printf("\n中序遍历:");
	inorder(T);
	printf("\n后序遍历:");
	postorder(T);
	
	return 0;
} 
上一篇:链队列基本操作实现(C语言)


下一篇:【数据结构学习】双向循环链表的插入、删除、查找、遍历、释放操作的C语言实现