理论原理:
![](https://i-blog.csdnimg.cn/blog_migrate/fbb8275c9adaf4d31f2b233226099362.png)
代码实现:
#include <iostream>
using namespace std;
struct Binary_Tree_Node
{
char data;
Binary_Tree_Node *lchild;
Binary_Tree_Node *rchild;
};
//'#'表示法创建二叉树
Binary_Tree_Node* createBinaryTree()
{
cin.sync();
char ch;
cin>>ch;
Binary_Tree_Node *root;
if(ch == '#')
{
root=NULL;
}
else
{
root=new Binary_Tree_Node;
root->data=ch;
root->lchild=createBinaryTree();
root->rchild=createBinaryTree();
}
return root;
}
//先序遍历
void Traverse(Binary_Tree_Node *root)
{
if(root==NULL)
{
return;
}
cout<<root->data;
Traverse(root->lchild);
Traverse(root->rchild);
}
int main()
{
//必须包含中序遍历才能确定一颗树
//此处使用'#'表示法唯一标识一颗树
Binary_Tree_Node *root=createBinaryTree();
Traverse(root);
return 0;
}
运行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/7578b81de66d93d6299da86b65ff7c04.png)