Design algorithm to find the mid-order traversal sequence of binary tree.
[Input form] A line of character string. This line is the pre-order traversal sequence of the extended binary tree, which is used to construct the binary tree.
[Output form] Mid-order traversal sequence in binary tree.
[Sample input] AB # D ## C ##
[Sample output]
BDAC
analysis:
1. First build a binary tree and nodes
2. Use recursion to perform in-order traversal
3. Print output
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;
};
Construct a binary tree
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;
}
Output function
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 function
int main()
{
BiTree<char>t1;//对应自己写的类
t1.InOrder();//对应自己写的输出函数
}