在网上看了很多二叉树前序遍历非递归实现,有的很巧。但是我想能不能就是用最原始的办法,通过栈了模拟递归函数的调用来实现。最后费了好大劲实现了。
要点是要用两个栈来模拟递归:
第一个栈s记录当下的节点;
第二个栈sp记录当下的返回点,也就是在递归函数中是返回到了左节点遍历完,还是右节点遍历完。
// BTree.h
template <class T>
class BTree {
template <class T1> friend void visit (BTree<T1> *);
template <class T1> friend void pre_order_r(BTree<T1> *);
template <class T1> friend void pre_order_n(BTree<T1> *);
public:
BTree(const T& e, BTree<T> *l, BTree<T> *r){
data = e;
left = l;
right = r;
}
private:
T data;
BTree<T> *left, *right;
};
template <class T>
void visit(BTree<T> *t)
{
if (t!=NULL) {
std::cout<<t->data<<" ";
}
}
template <class T>
void pre_order_r(BTree<T> *t)
{
BTree<T> *p = t;
if (p != NULL) {
visit(p);
pre_order_r(p->left);
pre_order_r(p->right);
}
}
template <class T>
void pre_order_n(BTree<T> *t)
{
std::stack<BTree<T>* > s;
std::stack<int> rp;
BTree<T> *p = t;
s.push(p);
rp.push(0);
int times = 1;
while (times++ <= 30) {
//std::cout<<"size is "<<s.size()<<std::endl;
if (p == NULL) {
s.pop();
rp.pop();
p = s.top();
if (s.empty()) {
std::cout<<"over"<<std::endl;
break;
} else {
if (rp.top() == 1) {
p = p->right;
rp.top() = 2;
rp.push(0);
s.push(p);
continue;
} else {
p = NULL;
continue;
}
}
} else {
visit(p);
p = p->left;
s.push(p);
rp.top() = 1;
rp.push(0);
continue;
}
}
}
// BTree.cpp
#include <iostream>
#include <stack>
#include "BTree.h"
int main()
{
BTree<int> n8(8, NULL, NULL);
BTree<int> n7(7, NULL, NULL);
BTree<int> n6(6, &n7, NULL);
BTree<int> n3(3, NULL, &n6);
BTree<int> n4(4, NULL, NULL);
BTree<int> n2(2, &n3, &n4);
BTree<int> n5(5, &n8, NULL);
BTree<int> n1(1, &n2, &n5);
std::stack<BTree<int>*> s;
std::cout<<(s.empty())<<std::endl;
//pre_order_r(&n1);
//pre_order_n(&n1);
system("pause");
}