设计算法求二叉树的中序遍历序列。
【输入形式】一行字符串,该行是扩展二叉树的前序遍历序列,用于构造二叉树。
【输出形式】二叉树中的中序遍历序列。
【样例输入】AB#D##C##
【样例输出】
BDAC
分析:
1.首先要建立一棵二叉树和节点
2.利用递归进行中序遍历
3.打印输出
struct BiNode//节点
{
DataType data;
BiNode<DataType>*lchild,*rchild;
};
template<typename DataType>//二叉树
class BiTree
{
public:
BiTree()
{
root=Create();
}
void InOrder()
{
InOrder(root);
}
private:
BiNode<DataType>*Create();
void InOrder(BiNode<DataType>*bt);
BiNode<DataType>*root;
};
构造二叉树
template<typename DataType>
BiNode<DataType>*BiTree<DataType>::Create()
{
BiNode<DataType>*bt;
char ch;
cin>>ch;
if(ch=='#')
bt=NULL;
else
{
bt=new BiNode<DataType>;
bt->data=ch;
bt->lchild=Create();
bt->rchild=Create();
}
return bt;
}
输出函数
template<typename DataType>
void BiTree<DataType>::InOrder(BiNode<DataType>*bt)
{
if(bt==NULL)
return;
else
{
InOrder(bt->lchild);
cout<<bt->data;
InOrder(bt->rchild);
}
}
main函数
int main()
{
BiTree<char>t1;//对应自己写的类
t1.InOrder();//对应自己写的输出函数
}