二叉树中序遍历非递归
#include <iostream>
#include<stack>
using namespace std;
struct BiTree {
int data;
BiTree *lChild, *rChild;
BiTree() {
data = 0;
lChild = NULL;
rChild = NULL;
}
BiTree(int x) {
data = x;
lChild = NULL;
rChild = NULL;
}
BiTree(int x, BiTree *l, BiTree *r) {
data = x;
lChild = l;
rChild = r;
}
};
stack<BiTree> s;
void InOrder(BiTree *T) {
BiTree *p = T;
while (p || !s.empty()) {
if (p) {
s.push(*p);
p = p->lChild;
} else {
BiTree temp = s.top();
s.pop();
cout << temp.data << " ";
p = temp.rChild;
}
}
}
int main() {
BiTree t6(6);
BiTree t4(4, &t6, NULL);
BiTree t2(2, NULL, &t4);
BiTree t5(5);
BiTree t3(3, NULL, &t5);
BiTree t1(1, &t2, &t3);
InOrder(&t1);
return 0;
}