HDU 1710-Binary Tree Traversals

來源:互聯網
上載者:User

好久沒好好AC了, 這學期的資料結構也沒好好學。惡補ing...

 

題目大意:告訴二叉樹的先序序列和中序序列,求後序序列。

思路:先序建立二叉鏈表,再後續遍曆二叉樹。

 

#include <cstdio><br />using namespace std;<br />typedef struct Binary<br />{<br /> int data;<br /> Binary *lchild, *rchild;<br /> Binary()<br /> {<br /> lchild = NULL;<br /> rchild = NULL;<br /> }<br />}*BitTree;<br />int pre[1010], in[1010];<br />void Build(BitTree &root, int len, int pst, int ped, int inst, int ined)//先序建樹<br />{<br /> int i, l_len = 0;<br /> if (len <= 0)<br /> return ;<br /> root = new Binary;<br /> root->data = pre[pst];<br /> for (i = inst; i <= ined; i++)<br /> {<br /> if (in[i] == pre[pst])<br /> {<br /> l_len = i - inst;<br /> break;<br /> }<br /> }<br /> Build(root->lchild, l_len, pst+1, pst+l_len, inst, i-1);<br /> Build(root->rchild, len-1-l_len, pst+l_len+1, ped, i+1, ined);<br />}<br />void Travel(Binary *root)//後序遍曆<br />{<br /> int i;<br /> if (root)<br /> {<br /> Travel(root->lchild);<br /> Travel(root->rchild);<br /> printf("%d ", root->data);<br /> }<br />}<br />int main()<br />{<br /> int i, n;<br /> BitTree root;</p><p> while (scanf("%d", &n) != EOF)<br /> {<br /> for (i = 0; i < n; i++)<br /> {<br /> scanf("%d", &pre[i]);<br /> }<br /> for (i = 0; i < n; i++)<br /> {<br /> scanf("%d", &in[i]);<br /> }<br /> Build(root, n, 0, n-1, 0, n-1);<br /> Travel(root->lchild);<br /> Travel(root->rchild);<br /> printf("%d/n", root->data);<br /> }<br /> return 0;<br />} 

 

聯繫我們

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