二叉樹的先序遍曆非遞迴實現方法

來源:互聯網
上載者:User
#include "iostream"using namespace std;struct node {int key;node* left;node* right;node(){}node(int x):key(x),left(NULL),right(NULL){}};struct Tree {node* root;Tree():root(NULL){}};void push(node* S,node x){S[0].key++;S[S[0].key]=x;}node* pop(node* S){if (S[0].key==0) {return NULL;}S[0].key--;return &S[S[0].key+1];}void print_tree(Tree* T){node stack[20]={0};node* t=T->root;while (1) {//如果有節點,則一直往下輸出所有的最左邊的結點,同時用棧儲存所有的結點cout<<t->key<<' ';push(stack,*t);if (t->left) {t=t->left;}else{do{//如果結點的右孩子不存在,則一直彈棧,測試上一個結點,//直到找到一個結點,它的右孩子存在為止,則將指標指向它的右孩子,重複外迴圈t=pop(stack);if (t==NULL) {return;}}while (t->right==NULL) ;t=t->right;}}}void main(){node A[11];for(int i=1;i<=10;i++){int key,left,right;cin>>key>>left>>right;A[i].key=key;if (left) {A[i].left=&A[left];}elseA[i].left=NULL;if (right) {A[i].right=&A[right];}elseA[i].right=NULL;}Tree* T=new Tree();T->root=&A[6];print_tree(T);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.