題目:列印二元樹所有從根到葉子路徑。
分析:採用二元樹的非遞迴後根遍曆,每次輸出節點內容的時候判斷是否為葉子節點,如果是則逆序列印棧裡內容。
例子:
輸入二元樹如下:
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 />
擴充:
相關面試題還有求所有路徑中和為某值的路徑,只需要在棧的基礎上加一個和,輸出時判斷即可。