层序遍历一颗二叉树。给定一颗二叉树如下:
输出结果:
1
2 3
4 5 6
7 8
给出书上的两种实现:
#include <iostream> #include <cstring> #include <vector> using namespace std; struct node{ int data; node* left; node* right; }; void creattree(node* &root) { root=new node; root->data=1; node* t2=new node; t2->data=2; root->left=t2; node* t3=new node; t3->data=3; root->right=t3; node* t4=new node; t4->data=4; t2->left=t4; node* t5=new node; t5->data=5; t2->right=t5; node* t6=new node; t6->data=6; t3->left=NULL; t3->right=t6; t6->left=t6->right=NULL; t4->left=t4->right=NULL; node* t7=new node; t7->data=7; t7->left=t7->right=NULL; t5->left=t7; node* t8=new node; t8->data=8; t8->left=t8->right=NULL; t5->right=t8; } int printatlevel(node* root,int level) { if(!root||level<0)return 0; if(level==0){ cout<<root->data<<" "; return 1; } return printatlevel(root->left,level-1)+printatlevel(root->right,level-1); } void printbylevel(node* root) { for(int level=0;;level++) { if(!printatlevel(root,level)) break; cout<<endl; } } void destroy(node* root) { if(root->left==NULL&&root->right==NULL){ delete root; return ; } if(root->left)destroy(root->left); if(root->right)destroy(root->right); delete root; } void print_new(node * root) { if(root==NULL) return ; vector<node*> vec; vec.push_back(root); int cur=0,last=1; while(cur<vec.size()) { last=vec.size(); while(cur<last) { cout<<vec[cur]->data<<" "; if(vec[cur]->left) vec.push_back(vec[cur]->left); if(vec[cur]->right) vec.push_back(vec[cur]->right); cur++; } cout<<endl; } } int main() { node *root; creattree(root); //printatlevel(root,1); //printbylevel(root); print_new(root); destroy(root); //回收由new分配的内存 return 0; }