#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
struct TreeNode{
int data;
TreeNode *leftchild;
TreeNode *rightchild;
};
void InOrder(TreeNode* tree){//中序遍历
if(tree != NULL){
InOrder(tree->leftchild);
printf("%c ",tree->data);
InOrder(tree->rightchild);
}
}
void LevelOrder(TreeNode* root){//层次遍历
queue<TreeNode*> myQueue;
myQueue.push(root);
while(!myQueue.empty()){
TreeNode* current = myQueue.front();
myQueue.pop();
if(current->leftchild !=NULL){
LevelOrder(current->leftchild);
}
if(current->rightchild != NULL){
LevelOrder(current->rightchild);
}
}
return;
}
TreeNode* Build(int& position,string str){//树的生成 要用引用&position
char c = str[position++];
if(c == '#'){
return NULL;
}else{
TreeNode* node = new TreeNode();
node->data = c;
node -> leftchild = Build(position,str);
node -> rightchild = Build(position,str);
return node;
}
}
int main(){
string str;
while(cin>>str){
int position = 0;
TreeNode* root = Build(position,str);
InOrder(root);
printf("\n");
}
return 0;
}
树的生成和遍历
最新推荐文章于 2023-04-24 09:30:00 发布