中序和前序序列构建二叉树

由中序可以确定多个二叉树,但由中序和前序(或者后序)则可以唯一确定一个二叉树,具体构造方法可以通过递归算法实现:

前序序列:ABHFDECKG

中序序列:HBDFAEKCG

前序字母A将中序划分为两个子序列:((HBDF)A(EKCG)),左子树由(HBDF)构成,右子树由(EKCG)构成

(1)左子树作为一个新的树构建,中序序列为HBDF,前序序列为BHFD

(2)右子树作为一个新的树构建,中序序列为EKCG,前序序列为ECKG

层层划分,最后直到叶子节点,中序为H,则前序也为H,然后再划分H,它的左右子树为空,递归截止,往上回溯!

分解图如下:


具体代码如下:

/*************************************************************************
    > File Name: geneteBinaryTree.cpp
    > Author: ltf
    > Mail: @qq.com 
    > Created Time: Fri 25 Mar 2016 07:25:07 PM CST
 ************************************************************************/

#include<iostream>
using namespace std;

typedef struct Tree
{
	Tree *left;
	Tree *right;
	char value;
}*pTree;

// LVR[0,k,n]
// LVR[0] increase always ,yet n is the tail 
pTree generateBinaryTree(char *VLR,char *LVR,int n)
{
	int k = 0;
	if(n == 0)
		return NULL;
//if input right  k < n
	while(VLR[0] != LVR[k]) k++;

	Tree *root = new Tree();
	root->value = LVR[k];
// [0,n)
	root->left  = generateBinaryTree(VLR+1,LVR,k);
// new range,[k+1,n-(k+1)) and start of LVR shall be VLR[k+1]
	root->right = generateBinaryTree(VLR+k+1,LVR+k+1,n-k-1);

	return root;
}
void printPreOrder(Tree *root)
{
	if(root != NULL)
	{
		cout << root->value;
		printPreOrder(root->left);
		printPreOrder(root->right);
	}
}
int main()
{
	char VLR[20],LVR[20];
	cout << "input the number"<<endl;
	int i=0;int n;
	cin >> n;
	cin.get();
	cout << "preOrder number"<< endl;
	for(i=0; i<n ;i++)
	{
		cin.get(VLR[i]);
	}
	cin.get();
	cout << "inOrder number" << endl;
	for(i=0; i<n ;i++)
	{
		cin.get(LVR[i]);
	}
	Tree *root =  generateBinaryTree(VLR ,LVR , n);

	cout << "preOrder after generate tree:"<< endl;
	printPreOrder(root);
	cout << endl;
	return 0;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值