用递归的方法建立,先左后右。依次创建左右子树。
#include<iostream>
#include<stack>
using namespace std;
struct Node{
char data;
Node *lchild;
Node *rchild;
};
Node*createTree(){
char x;
cin>>x;
if(x=='#')return NULL;
Node *root=new Node;
root->data=x;
root->lchild=createTree();
root->rchild=createTree();
return root;
}
void preorder(Node* root){
if(root){
cout<<root->data<<" ";
preorder(root->lchild);
preorder(root->rchild);
}
}
int main(){
Node *root=createTree();
preorder(root);
return 0;
}
运算结果:输入的数据按照先序遍历的顺序输入,输出结果也是先序遍历。