演算法學習,演算法學習網站

來源:互聯網
上載者:User

演算法學習,演算法學習網站
樹的遍曆

這三種遍曆方法其實都很簡單的,舉例來說:

   a /   \b     c

這個是例子下面講下這三個是如何遍曆的。

下面都是遞迴方法,非遞迴方法請看我另一篇部落格:http://blog.csdn.net/alps1992/article/details/38308285

struct TreeNode;typedef TreeNode* Node;typedef int EleType;struct TreeNode{    Node lchild;    Node rchild;    EleType data;};


先序遍曆

先序遍曆,就是從上到下,從左至右,遇到一個就遍曆,上面這個例子遍曆的序列就是:a b c
遞迴代碼如下: 

void PreOrderTree(Node node){    if (node != NULL) {        printf("%d\n",node->data);        PreOrderTree(node->lchild);        PreOrderTree(node->rchild);    }}


中序遍曆

中序遍曆的序列:b a c 其實中序遍曆就是先從左至右,來遍曆,先找到最左的,然後找到,它的右孩子,沒有的話再找父親,輸出,最後輸出右兄弟。
代碼如下:

}void InOrderTree(Node node){    if (node != NULL) {        InOrderTree(node->lchild);        printf("%d\n",node->data);        InOrderTree(node->rchild);    }}


後序遍曆

後序遍曆的序列:a c b 其實後序遍曆就是把中序遍曆的父親在它右兄弟輸出後再輸出。
代碼如下:

<pre name="code" class="cpp">void AfterPreOrderTree(Node node){    if (node != NULL) {        AfterPreOrderTree(node->lchild);        AfterPreOrderTree(node->rchild);        printf("%d\n",node->data);    }}




聯繫我們

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