#include <cstdio>
#include <iostream>
#include <string>
#include <queue>
using namespace std;
void visit(char c){
cout<<c<<" ";
return ;
}
struct TreeNode{
char data;
TreeNode* leftchild;
TreeNode* rightchild;
TreeNode(char c):data(c),leftchild(NULL),rightchild(NULL){} //构造函数 nullptr;
};
void PreOrder(TreeNode* root){
if(root == NULL){
return;
}
visit(root->data);
PreOrder(root->leftchild);
PreOrder(root->rightchild);
return;
}
void InOrder(TreeNode* root){
if(root == NULL){
return;
}
InOrder(root->leftchild);
visit(root->data);
InOrder(root->rightchild);
return;
}
void PostOrder(TreeNode* root){
if(root == NULL){
return;
}
PostOrder(root->leftchild);
PostOrder(root->rightchild);
cout<<root->data;
return;
}
void LevelOrder(TreeNode* root){
queue<TreeNode*>myQueue;
if(root != NULL){
myQueue.push(root);
}
while(!myQueue.empty()){
TreeNode* current =myQueue.front();
myQueue.pop();
visit(current->data);
if(current->leftchild!= NULL){
myQueue.push(current->leftchild);
}
if(current->rightchild != NULL){
myQueue.push(current->rightchild);
}
}
return;
}
TreeNode* Build(int& position,string str){ //给出先序遍历字符串建立二叉树 position 使用引用,会发生改变。
char c = str[position++];
if(c == '#'){
return NULL;
}
TreeNode* root = new TreeNode(c); //建立新的结点,c为根节点。
root->leftchild = Build(position,str);
root->rightchild = Build(position,str);
return root;
}
int main(void){
string str;
while(cin>>str){
int position = 0 ;
TreeNode* root = Build(position,str);
InOrder(root);
cout<<endl;
}
return 0;
}
这里给出的二叉树先序遍历序列,通过字符的位置来建立二叉树。