重建二叉树

来源:互联网 发布:centos 6.5 iso下载 编辑:程序博客网 时间:2024/06/05 20:07

题目:输入某二叉树的前序遍历和中序遍历的结果 请重建出该二叉树 假设输入的前序遍历和中序遍历的结果中都不含重复的数字 例如输入的前序遍历{1,2,4,7,3,5,6,8,}和

中序遍历{4,7,2,1,5,3,8,6} 则重建出来的二叉树如图所示 并输出他们的头结点 二叉树的节点定义如下




struct BinaryTreeNode{int m_nValue;BinaryTreeNode * m_pLeft;BinaryTreeNode * m_pRight;};


在二叉树的前序遍历序列中 第一个数字总是树根节点的值

但是在中序遍历中 根节点的值在序列的中间 左子树的节点值位于根节点的值的左边 而右子树位于根节点的右边 因此需要扫描中序遍历 才能找到根节点的值  根节点的前一个节点为左孩子 后一个节点 为右孩子  因此我们可以构建出 当前节点的左右孩子 然后找出左右子树 用同样的方法去构造左右子树

#include <iostream>using namespace std;struct BinaryTreeNode{int m_nValue;BinaryTreeNode * m_pLeft;BinaryTreeNode * m_pRight;};BinaryTreeNode *construct(int *p,int *pend,int *s,int *send){BinaryTreeNode *root=new BinaryTreeNode();int rvalue=p[0];root->m_nValue=rvalue;root->m_pLeft=root->m_pRight=NULL;if(p== pend){if( send==s && *s==rvalue)return root;elsethrow std::exception("Error ~!");}int *templeft=s;while ( *templeft!=rvalue && templeft <=send )templeft++;if(templeft==send &&  *templeft !=rvalue)throw std::exception("Error~!");int left=templeft-s;int *leftend=p+left;if(left>0)root->m_pLeft=construct(p+1,leftend,s,templeft-1);if(left<send-s)root->m_pRight=construct(leftend+1,pend,templeft+1,send);return root;}BinaryTreeNode * rebulid(int *p,int *s,int n){if (p==NULL || s==NULL || n==0)return 0;elsereturn construct(p,p+n-1,s,s+n-1);}void vist(BinaryTreeNode *p){if(p!=NULL)cout<<p->m_nValue<<' ';if(p->m_pLeft!=NULL)vist(p->m_pLeft);if(p->m_pRight!=NULL)vist(p->m_pRight);}int main(){int a[]={1,2,4,7,3,5,6,8};int b[]={4,7,2,1,5,3,8,6};int n=8;BinaryTreeNode *p=new BinaryTreeNode();p=rebulid(a,b,n);vist(p);return 0;}






0 0