先序构造二叉树、层次遍历输出
#include<iostream> #include<queue> using namespace std; //树结构定义 typedef struct node{ char val; struct node* left; struct node* right; }TreeNode,*Tree; //先序构造二叉树 void CreateTree(Tree& t){ char x; cin>>x; if(x == '.') t = NULL; //遇到'#',t置空 else{ t = new TreeNode; //创建一个新结点,让t指向它 t->val = x; //新结点赋值x CreateTree(t->left); //递归的创建左结点 CreateTree(t->right); //递归的创建右结点 } } //层次遍历输出二叉树 void levelOrder(Tree& t) { if(t == NULL) return; queue<TreeNode*> q; q.push(t); while(!q.empty()){ int n = q.size(); for(int i = 0;i<n;i++){ TreeNode* s = q.front(); cout<<s->val<<" "; q.pop(); if(s->left) q.push(s->left); if(s->right) q.push(s->right); } cout<<endl; } } int main(){ Tree t; CreateTree(t); /* a b d # # e # # c f # # # */ levelOrder(t); }