由先序遍历和中序遍历建立二叉树

#include<iostream>  
#include<cstring>  
#include<cstdio>  
#include<cstdlib>  
#include<stack>  
#include<queue>  
using namespace std;
typedef int ElemType;
typedef struct BinaryTreeNode
{
ElemType data;
BinaryTreeNode *left, *right;
}BinaryTreeNode;
//二叉树的建立3 根据先序序列和中序序列建立一个二叉树     先序:DBACEGF     中序:ABCDEFG   令pre[]="DBACEGF"   in[]="ABCDEFG"  
BinaryTreeNode * CreateBinaryTree(ElemType * pre, ElemType *in, int length)//此种建立二叉树的方法本质上是先建立根结点 再建立左子树,再建立右子树  
{
if (length <= 0 || pre == NULL || in == NULL)递归出口:长度为0时表示建树完毕  
{
return NULL;
}
ElemType rootValue = pre[0];
BinaryTreeNode * root = new BinaryTreeNode();//建立根节点  
root->data = rootValue;
root->left = root->right = NULL;
int leftLength, rightLength, i = 0;//左子树的长度,右子树的长度  ,下面的代码就是找到左右子树的元素,建立左右子树
while (i<length&&in[i] != rootValue)
{
i++;
}
leftLength = i;
rightLength = length - leftLength - 1;//注意对个一个遍历的序列一定满足rightLength+leftLength+1=length;左子树长度加上右子树长度加一个根结点的长度等于树所有结点的长度。  
if (leftLength>0)//建立左子树  
{
root->left = CreateBinaryTree(pre + 1, in, leftLength);此处的关键在于寻找右子树后序序列的起始地址,和右子树的中序序列的起始地址  
}
if (rightLength>0)//建立右子树  
{
root->right = CreateBinaryTree(pre + length - rightLength, in + length - rightLength, rightLength);此处的关键在于寻找右子树后序序列的起始地址,和右子树的中序序列的起始地址  
// 上一句等价于root->right =CreateBinaryTree(pre+1+leftLength,in+1+leftLength,rightLength);  
}
return root;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值