C语言学习笔记——根据二叉树的后序和中序遍历序列,求这棵树的先序和层次遍历序列

 

     先根据二叉树的后序和中序遍历序列,用递归的方法创建出这棵树,然后用的自定义栈的先序和层次方法遍历。

     
         

    输入:  7                                                         

                  2 3 1 5 7 6 4   
                  1 2 3 4 5 6 7

    输出:

C语言学习笔记——根据二叉树的后序和中序遍历序列,求这棵树的先序和层次遍历序列_第1张图片

C语言学习笔记——根据二叉树的后序和中序遍历序列,求这棵树的先序和层次遍历序列_第2张图片

 

#include 
#define max 50
typedef int Elemtype;
int pre[max], in[max], post[max];

typedef struct BTNode{
	Elemtype data;
	struct BTNode *lchild, *rchild;
}BTree;

/* according to the postorder and inorder travelsal
	sequences to create a binary tree */
BTree* create(Elemtype postL, Elemtype postR, Elemtype inL, Elemtype inR){
	if(postL > postR)
		return NULL;
	BTree *root;
	root =  (BTree*)malloc(sizeof(BTree));
	root->data = post[postR];                //后序遍历序列的最后一个结点就是当前树的根结点
	int k;
	for(k = inL; k <= inR; k++){
		if(in[k] == post[postR])             //寻找当前树的根节点在中序遍历序列中的位置
			break;
	}
	int numLeft = k - inL;                   //root的左子树的结点总数
	root->lchild = create(postL, postL + numLeft - 1, inL, k - 1);  //root的左孩子所在的区间:中序 in[inL, k-1]
																	//后序post[postL, postL + numLeft - 1]
	root->rchild = create(postL + numLeft, postR - 1, k + 1, inR);
	return root;                                                    //递归返回根结点地址
}

/* preorder traversal bases on user-defined stack*/
void preorderstack(BTree *root){
	BTree *stack[max];                      //自定义顺序栈
	int top = -1;                           //栈顶指针
	stack[++top] = root;                    //根结点进栈
	BTree *p;
	while(top != -1){
		p = stack[top--];                   //出栈,访问根
  		printf("%d ", p->data);
  		if(p->rchild != NULL)               //若右孩子存在,让它进栈
			stack[++top] = p->rchild;       //注意,先让右孩子入栈
		if(p->lchild != NULL)               //若左孩子存在,让它进栈
			stack[++top] = p->lchild;
	}
}

/* level-order traversal bases on user-defined stack*/
void levelorder(BTree *root){
	BTree *queue[max];                      //自定义顺序循环队列
	int front =0, rear = 0;                 //队头/尾
    rear = (rear +1) % max;
	queue[rear] = root;                     //根结点进队
	BTree *p;
	while(front != rear){
  		front = (front + 1)%max;
  		p = queue[front];
  		printf("%d ", p->data);
  		if(p->lchild != NULL){
  		    rear = (rear + 1) % max;
			queue[rear] = p->lchild;
		}
		if(p->rchild != NULL){
   			rear = (rear + 1) % max;
			queue[rear] = p->rchild;
		}
	}
}

int main(){
	int n;        //树的结点个数
	printf("Total number of nodes: ");
	scanf("%d", &n);
	printf("Postorder: ");
	for(int i = 0; i < n; i++){
		scanf("%d", &post[i]);
	}
	printf("Inorder: ");
	for(int i = 0; i < n; i++){
		scanf("%d", &in[i]);
	}
	BTree *root = create(0, n - 1, 0, n - 1);
	printf("Preorder: ");
	preorderstack(root);
	
	printf("\nLevelorder: ");
	levelorder(root);
	return 0;
}

 

你可能感兴趣的:(C语言笔记)