中根后根遍历并构造二叉树、有错求大神帮忙看一下
程序输出不了结果、求大神帮忙看一下BinaryNode.h
#include "BinaryNode.h"
template<class T>
class BinaryTree
{
public:
BinaryNode<T>*root;
BinaryTree();
BinaryTree(T inlist[],T postlist[],int n);
void inOrder();
void postOrder();
private:
void inOrder(BinaryNode<T>*p);
void postOrder(BinaryNode<T>*p);
BinaryNode<T>*create(T inlist[],T postlist[],int inStart,int postStart,int n);
};
template <class T>
BinaryTree<T>::BinaryTree() //构造空二叉树
{
root=NULL;
}
template <class T> //中根后跟构造二叉树、n指定序列长度
BinaryTree<T>::BinaryTree(T inlist[],T postlist[],int n)
{
root=create(inlist, postlist,0,0,n);
}
template<class T> //中根后根创建子树,根节点是inlist[i],返回根节点指针
BinaryNode<T>*BinaryTree<T>::create(T inlist[],T postlist[],int inStart,int postStart,int n)
{
BinaryNode<T>*p=NULL;
if(n>0)
{
T elem=inlist[inStart]; //根节点值
int i=0;
while (i<n && elem!=postlist[postStart+i])
i++;
p->left=create(inlist,postlist,inStart,postStart,i);
p=new BinaryNode<T>(elem);
p->right=create(inlist,postlist,inStart+i+1,postStart+i+1,n-1-i);
}
return p;
}
template<class T>
void BinaryTree<T>::inOrder()
{
cout<<"中根次序遍历二叉树:";
inOrder(root);
cout<<endl;
}
template<class T>
void BinaryTree<T>::inOrder(BinaryNode<T>*p)
{
if(p!=NULL);
{
inOrder(p->left);
cout<<p->data<<" ";
inOrder(p->right);
}
}
template<class T>
void BinaryTree<T>::postOrder()
{
cout<<"后根次序遍历二叉树:";
postOrder(root);
cout<<endl;
}
template<class T>
void BinaryTree<T>::postOrder(BinaryNode<T>*p)
{
if(p!=NULL);
{
postOrder(p->left);
postOrder(p->right);
cout<<p->data<<" ";
}
}
主函数
#include <iostream.h>
#include "BinaryTree.h"
int main()
{
char inlist[]="DGBAECHF";
char postlist[]="GDBEHFCA";
BinaryTree<char>bitree(inlist,postlist,8);
bitree.inOrder();
bitree.postOrder();
return 0;
}