已知完全二叉树的前序遍历数组,求层次遍历与后序遍历

注意:此种方法仅适用于完全二叉树满二叉树!!!此种方法仅适用于完全二叉树或满二叉树!!!此种方法仅适用于完全二叉树或满二叉树!!!

先根据前序数组得到树的各个结点下标对应的值。例如对于i结点,左子结点是2i,右子结点是2i+1.

层次遍历数组:由上已求得tree

后序遍历数组:通过后序遍历可得到pos

程序代码如下:

#include<iostream>
using namespace std;

int n = 5,index = 0;
int pre[5] = {10,6,2,7,15};//已知完全二叉树的前序序列数组 
int tree[6],pos[6];

void getTree(int x){//获取完全二叉树各结点对应的值 
	if(x > n)
		return;
	tree[x] = pre[index++];
	getTree(x<<1);
	getTree((x<<1)+1);	
}

void getPost(int x){//求完全二叉树的后序遍历数组 
	if(x > n)
		return;
	getPost(x<<1);
	getPost((x<<1)+1);	
	pos[index++] = tree[x];
}

int main(){
	index = 0;
	getTree(1);
	
	cout<<"输出层次遍历: "; 
	for(int i=1;i<=n;i++)//输出层次遍历 
		cout<<tree[i]<<" ";
	cout<<endl; 
	
	index = 0;
	getPost(1);
	cout<<"输出后序遍历: ";
	for(int i=0;i<n;i++)//输出后序遍历 
		cout<<pos[i]<<" ";
	cout<<endl; 
	
	return 0;
}

运行结果:

猜你喜欢

转载自blog.csdn.net/qq_29762941/article/details/82872802