C++二叉樹先序、中序、後序遍曆

來源:互聯網
上載者:User

標籤:

 1 #include <iostream> 2 using namespace std; 3  4 typedef struct BTNode 5 { 6     char data; 7     struct BTNode * lchild; 8     struct BTNode * rchild; 9 }BTNode;10 11 BTNode * initBTNode()12 {13     BTNode *node = (BTNode*)malloc(sizeof(BTNode));14     node->lchild=0;15     node->rchild=0;16     return node;17 }18 19 BTNode * init(BTNode *p)20 {21     BTNode *A=initBTNode();22     BTNode *B=initBTNode();23     BTNode *C=initBTNode();24     BTNode *D=initBTNode();25     BTNode *E=initBTNode();26     BTNode *F=initBTNode();27         28     A->data=‘A‘;29     B->data=‘B‘;30     C->data=‘C‘;31     D->data=‘D‘;32     E->data=‘E‘;33     F->data=‘F‘;34     35     C->lchild=E;36     C->rchild=F;37     B->lchild=D;38     A->rchild=C;39     A->lchild=B;40 41     p=A;42     return p;43 }44 45 void visit(BTNode *p)46 {47     cout << p->data << " ";48 }49 50 void preorder(BTNode *p)51 {52     if(p!=0)53     {54         visit(p);55         preorder(p->lchild);56         preorder(p->rchild);57     }58 }59 60 void inorder(BTNode *p)61 {62     if(p!=0)63     {64         inorder(p->lchild);65         visit(p);66         inorder(p->rchild);67     }68 }69 70 void postorder(BTNode *p)71 {72     if(p!=0)73     {74         postorder(p->lchild);75         postorder(p->rchild);76         visit(p);77     }78 }79 80 int main(int argc, char* argv[])81 {82     BTNode *node=new BTNode;83     BTNode *p=init(node);84     cout << "先序遍曆:" ;85     preorder(p);86     cout << endl;87     cout << "中序遍曆:" ;88     inorder(p);89     cout << endl;90     cout << "後序遍曆:" ;91     postorder(p);92     cout << endl;93     return 0;94 }


 

C++二叉樹先序、中序、後序遍曆

聯繫我們

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