列印二元樹所有路徑

來源:互聯網
上載者:User

題目:列印二元樹所有從根到葉子路徑。

分析:採用二元樹的非遞迴後根遍曆,每次輸出節點內容的時候判斷是否為葉子節點,如果是則逆序列印棧裡內容。

例子:

輸入二元樹如下:

         1

        /  /

       2   3

      /  /

     4   5

         /  /

        6   7

輸出:1、2、4

         1、2、5、6

         1、2、5、7

         1、3

 

C/C++源碼:

#include <iostream><br />#include <stack><br />using namespace std;</p><p>struct node{<br /> node(int a):data(a),left(NULL),right(NULL),f(false){}<br /> int data;<br /> node *left, *right;<br /> bool f;<br />};</p><p>//dump the path from root to leaf<br />void dump(stack<node*> st){<br /> stack<node*> tmp;<br /> while(!st.empty()){<br /> tmp.push(st.top());<br /> st.pop();<br /> }<br /> while(!tmp.empty()){<br /> cout << tmp.top()->data << "/t";<br /> tmp.pop();<br /> }<br />}</p><p>//post order travel<br />void postOrder(node* r)<br />{<br /> node* tmp = r;<br /> stack<node*> s;<br /> while(!s.empty() || tmp!=NULL){<br /> while(tmp!=NULL){<br /> s.push(tmp);<br /> tmp = tmp->left;<br /> }<br /> if(s.top()->f){<br /> //if the node is leaf<br /> if(s.top()->left==NULL && s.top()->right==NULL){<br /> dump(s);<br /> cout << endl;<br /> }<br /> s.pop();<br /> }else{<br /> tmp = s.top()->right;<br /> s.top()->f =true;<br /> }<br /> }<br />}</p><p>int main()<br />{<br /> node* n1 = new node(1);<br /> node* n2 = new node(2);<br /> node* n3 = new node(3);<br /> node* n4 = new node(4);<br /> node* n5 = new node(5);<br /> node* n6 = new node(6);<br /> node* n7 = new node(7);<br /> n1->left = n2, n1->right = n3;<br /> n2->left = n4, n2->right = n5;<br /> n5->left = n6, n5->right = n7; </p><p> postOrder(n1);</p><p> return 0;<br />}<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.