編程之美讀書筆記—分層遍曆二叉樹

來源:互聯網
上載者:User

層序遍曆一顆二叉樹。給定一顆二叉樹如下:

輸出結果:

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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.