二叉樹的三種遍歷方式一直都是為人津津樂道的面試題,考察一個人對遞歸的理解讓他寫個三種遍歷方式是最簡單的考察方式了,那麼考察一個人對遞歸的理解更加深層次的方式就是讓他用循環模擬遞歸(就是把遞歸代碼轉換成非遞歸),一般想要實現這樣的東西是需要棧的,或許說使用棧的結構更加貼合函數棧的壓入和彈出,更加好理解
遞歸的三種遍歷方式分別為,前序遍歷,中序遍歷,後序遍歷,在考慮完了遞歸的寫法之後,非遞歸的寫法更加難;1 void PreOrder_NonR() 2 3 { 4 5 if (_root == NULL ) 6 7 { 8 9 return; 10 11 } 12 13 stack<BinaryTreeNode <T>*> s; 14 15 s.push(_root); 16 17 while (!s.empty()) 18 19 { 20 21 BinaryTreeNode<T >* top = s.top(); 22 23 cout << top->_data << " " ; 24 25 s.pop(); 26 27 if (top->_right) 28 29 { 30 31 s.push(top->_right); 32 33 } 34 35 if (top->_left) 36 37 { 38 39 s.push(top->_left); 40 41 } 42 43 } 44 45 cout << endl; 46 47 }
1 void InOrder_NonR() 2 3 { 4 5 stack<BinaryTreeNode <T>*> s; 6 7 BinaryTreeNode<T > *cur = _root; 8 9 while (cur || !s.empty()) 10 11 { 12 13 while (cur) 14 15 { 16 17 s.push(cur); 18 19 cur = cur->_left; 20 21 } 22 23 if (!s.empty()) 24 25 { 26 27 BinaryTreeNode<T > *top = s.top(); 28 29 cout << top->_data << " " ; 30 31 s.pop(); 32 33 cur = top->_right; 34 35 } 36 37 } 38 39 cout << endl; 40 41 }
1 void PostOrder_NonR() 2 3 { 4 5 stack<BinaryTreeNode <T> *> s; 6 7 BinaryTreeNode<T >* PreVisited = NULL; 8 9 BinaryTreeNode<T >* cur = _root; 10 11 while (cur || !s.empty()) 12 13 { 14 15 while (cur) 16 17 { 18 19 s.push(cur); 20 21 cur = cur->_left; 22 23 } 24 25 BinaryTreeNode<T > *top = s.top(); 26 27 if (top->_right == NULL || PreVisited == top->_right) 28 29 { 30 31 cout << top->_data << " " ; 32 33 s.pop(); 34 35 PreVisited = top; 36 37 } 38 39 else 40 41 { 42 43 cur = top->_right; 44 45 } 46 47 } 48 49 cout << endl; 50 51 }
這是我從我的筆記導出來的,話說縮進怎麼變成這德行了。。。