二叉樹遍曆

來源:互聯網
上載者:User

標籤:blog   io   ar   os   sp   div   on   log   bs   

#include <stdio.h>#include <stack>#include <queue>using namespace std;typedef char DataType;typedef struct BiTNode{DataType data;struct BiTNode *lchild,*rchild;}BITNode;typedef BiTNode* BiTree;//先序建立二叉樹int CreateBiTree(BiTree& T){DataType data;scanf("%c",&data);if(data == ‘#‘){T = NULL;}else{T = new BiTNode;T->data = data;CreateBiTree(T->lchild);CreateBiTree(T->rchild);}return 0;}void Visit(BiTree T){if(T->data != ‘#‘){printf("%c ",T->data);}}//先序遍曆void PreOrder(BiTree T){stack<BiTree> stack;BiTree p = T;while(p || !stack.empty()){if(p != NULL){stack.push(p);printf("%c ",p->data);p = p->lchild;}else{p = stack.top();stack.pop();p = p->rchild;}}}//中序遍曆void InOrder(BiTree T){stack<BiTree> stack;BiTree p = T;while(p || !stack.empty()){if(p != NULL){stack.push(p);p = p->lchild;}else{p = stack.top();printf("%c ",p->data);stack.pop();p = p->rchild;}}}//後序遍曆void PostOrder(BiTree T){BiTNode* p,*q;stack<BiTree> stack;q = NULL;    p = T;while(p != NULL || !stack.empty()){while(p != NULL){stack.push(p);            p = p->lchild;}if(!stack.empty()){p = stack.top();if(p->rchild == NULL || p->rchild == q){printf("%c ",p->data);q = p;stack.pop();p = NULL;}else{p = p->rchild;}}}}//層次遍曆void LevelOrder(BiTree T){BiTree p = T;queue<BiTree> queue;queue.push(p);while(!queue.empty()){p = queue.front();printf("%c ",p->data);queue.pop();if(p->lchild != NULL){queue.push(p->lchild);}if(p->rchild != NULL){queue.push(p->rchild);}}}//深度遍曆void DepthOrder(BiTree T){stack<BiTNode*> stack;stack.push(T);BiTNode* p;while(!stack.empty()){p = stack.top();printf("%c ",p->data);stack.pop();    if(p->rchild){stack.push(p->rchild);}if(p->lchild){stack.push(p->lchild);}}}//廣度遍曆void BreadthOrder(BiTree T){queue<BiTNode*> queue;queue.push(T);BiTNode* p;while(!queue.empty()){p = queue.front();queue.pop();printf("%c ",p->data);if(p->lchild){queue.push(p->lchild);}if(p->rchild){queue.push(p->rchild);}}}//ABC##DE#G##F###int main(int argc,char** argv){BiTree T;  CreateBiTree(T);  printf("先序遍曆:\n");  PreOrder(T);  printf("\n");  printf("中序遍曆:\n");  InOrder(T);  printf("\n");  printf("後序遍曆:\n");  PostOrder(T);  printf("\n");printf("層次遍曆:\n");  LevelOrder(T);  printf("\n");  printf("深度遍曆:\n");  DepthOrder(T);  printf("\n");printf("廣度遍曆:\n");  BreadthOrder(T);  printf("\n");printf("\n");  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.