当前位置:   article > 正文

4-15 根据后序和中序遍历输出先序遍历 (15分)本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。_本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果

本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果
#include <bits/stdc++.h>
using namespace std;
int post[50] , ino[50]; //定义全局变量
typedef struct btnode {
	int data;
	struct btnode *lchild,*rchild;
}btnode , *btree;

btree buildetree(int root,int start,int end);//root为后序根节点,start为中序开始,end为中序结尾
void DLRtree(btree bt);

int main(){
	btree bt;
	int N; cin>>N;
	int i;
	for(i=0;i<N;i++){
		int x; cin>>x;
		post[i] = x;
	}
	for(i=0;i<N;i++){
		int x; cin>>x;
		ino[i] = x;
	}
	bt = buildetree(N-1,0,N-1);//root在第N-1个位置,start开始在0位置,end在第N-1个位置
	cout<<"Preorder:";
	DLRtree(bt);
	return 0;
}

btree buildetree(int root,int start,int end){
	if(start>end) return 0;
	btree bt;
	int i;
	for(i=start;post[root] !=ino[i];i++);
	bt = new btnode;
	bt->data = post[root];
	bt->lchild = buildetree(root-(end-i)-1,start,i-1);
	bt->rchild = buildetree(root-1,i+1,end);
//下面图片
	return bt;
}

void  DLRtree(btree bt){
	if(bt == NULL) return;
    cout<<" "<<bt->data ;
    DLRtree(bt->lchild );
    DLRtree(bt->rchild );
}
![寻找root,statr,end的图](https://img-blog.csdnimg.cn/2020111817405153.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzUxMTk5MzA0,size_16,color_FFFFFF,t_70#pic_center)



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号