欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

树-1-二叉树的三种遍历

程序员文章站 2022-07-07 16:15:32
#include #include using namespace std; typedef struct BTNode{int data;struct BTNode *lchild;struct BTNode *rchild;}BTNode;void createTree(BTNode *&T){BTNode *a,*b,*c,*d,*e,*f,*g,*h,*i;T = (BTNode*)mall...
#include <iostream>
#include <malloc.h>
using namespace std; 

typedef struct BTNode{
	int data;
	struct BTNode *lchild;
	struct BTNode *rchild;
}BTNode;

void createTree(BTNode *&T){
	BTNode *a,*b,*c,*d,*e,*f,*g,*h,*i;
	
	T = (BTNode*)malloc(sizeof(BTNode));T->data = 1;
	a = (BTNode*)malloc(sizeof(BTNode));a->data = 2;
	b = (BTNode*)malloc(sizeof(BTNode));b->data = 3;
	c = (BTNode*)malloc(sizeof(BTNode));c->data = 4;
	d = (BTNode*)malloc(sizeof(BTNode));d->data = 5;
	e = (BTNode*)malloc(sizeof(BTNode));e->data = 6;
	f = (BTNode*)malloc(sizeof(BTNode));f->data = 7;
	g = (BTNode*)malloc(sizeof(BTNode));g->data = 8;
	h = (BTNode*)malloc(sizeof(BTNode));h->data = 9;
	i = (BTNode*)malloc(sizeof(BTNode));i->data = 10;

	T->lchild = a;T->rchild = b;
	a->lchild = c;a->rchild = NULL;
	b->lchild = d;b->rchild = e;
	c->lchild = NULL;c->rchild = f;
	d->lchild = g;d->rchild = h;
	e->lchild = NULL;e->rchild = i;
	f->lchild = NULL;f->rchild = NULL;
	g->lchild = NULL;g->rchild = NULL;
	h->lchild = NULL;h->rchild = NULL;
	i->lchild = NULL;i->rchild = NULL;	
}
void visit(BTNode *T){
	cout<<T->data<<"**"<<endl;
}
void preOrder(BTNode *T){
	if(T!=NULL){
	visit(T);
	
	preOrder(T->lchild);
	preOrder(T->rchild);
	}	
}
void inOrder(BTNode *T){
	if(T!=NULL){
	
	
	inOrder(T->lchild);
	visit(T);
	inOrder(T->rchild);
	}	
}
void postOrder(BTNode *T){
	if(T!=NULL){
	
	
	postOrder(T->lchild);
	postOrder(T->rchild);
	visit(T);
	}	
}

int main(int argc, char** argv) {	
	BTNode *T;
	
	createTree(T);
	
	postOrder(T);
	

	return 0;
}

本文地址:https://blog.csdn.net/qq_37409526/article/details/108994604