template<class T> void BinaryTree<T>:: PrevOrderNoRec() { if (_root == NULL) { return; } stack<Node*> s; s.push(_root); while (!s.empty()) { Node* top = s.top();//獲取棧頂 cout << top->_data << " "; s.pop(); //右孩子入棧 if (top->_rightChild) { s.push(top->_rightChild); } //左孩子入棧 if (top->_leftChild) { s.push(top->_leftChild); } } cout << endl; } template<class T> void BinaryTree<T>::InOrderNoRec() { if (_root == NULL) { return; } Node* cur = _root; stack<Node*> s; while (cur||!s.empty())//若是棧爲空而且cur==NULL跳出循環 { //找到最左下方的節點訪問 while (cur) { s.push(cur); cur = cur->_leftChild; } Node* top = s.top(); cout << top->_data << " "; s.pop(); //若是右子樹不爲空則按照中序遍歷,從新找到最左下角的繼續訪問 if (top->_rightChild) { cur = top->_rightChild; } //若是右子樹爲空,則cur==NULL,不會再次進入循環,直接出棧訪問 } cout << endl; } template<class T> void BinaryTree<T>::PosOrderNoRec() { if (_root == NULL) { return; } Node* cur = _root;//當前指針 Node* prev = NULL;//棧內的前驅指針 stack<Node*> s; while (cur || !s.empty()) { //找到最左下角節點 while (cur) { s.push(cur); cur = cur->_leftChild; } Node* top = s.top(); //若是右子樹爲空,或者以前訪問過則輸出 if (top->_rightChild == NULL || prev == top->_rightChild) { cout << top->_data << " "; prev = top;//出棧以前更新prev s.pop(); } else { cur = top->_rightChild; } } cout << endl; }