void NoRecursePreTraverse(BiTree tree){
stack<BiNode *> stack;
BiNode *node = tree;
while(node != NULL || !stack.empty()){
while(node != NULL){
cout << node->data <<" ";
stack.push(node);
node = node->lchild;
}
if(!stack.empty()){
node = stack.top();
node = node->rchild;
stack.pop();
}
}
}
void NoRecurseInTraverse(BiTree tree){
stack<BiNode *> stack;
BiNode *node = tree;
while(node != NULL || !stack.empty()){
while(node != NULL){
stack.push(node);
node = node->lchild;
}
if(!stack.empty()){
node = stack.top();
cout << node->data << " ";
stack.pop();
node = node->rchild;
}
}
}
struct BiTree_Flag{
BiNode *node;
bool flag;
};
void NoRecursePostTraverse(BiTree tree){
stack<BiTree_Flag> stack;
BiNode *node = tree;
BiTree_Flag node_flag;
while(node != NULL || !stack.empty()){
while(node != NULL){
node_flag.node = node;
node_flag.flag = false;
stack.push(node_flag);
node = node->lchild;
}
if(!stack.empty()){
node_flag = stack.top();
stack.pop();
if(node_flag.flag == false){
node_flag.flag = true;
stack.push(node_flag);
node = node_flag.node;
node = node->rchild;
}else{
cout << node_flag.node->data << " ";
}
}
}
}
思想:1)前序遍历:访问根节点,根节点放入栈中。访问左子树,如果左子数为空,栈弹出根节点,访问右子数。
2)中序遍历:根节点入栈,访问左子树。如果左子树为空,栈弹出根节点,访问根节点,访问右子树。
3)后续遍历:定义新的数据结构,为每一个节点定义一个标志位flag,false代表访问过一次,true代表访问过两次。
根节点入栈,flage设为FALSE。访问左子树。左子树为空,根节点弹出,如果flag为false,设为true,
访问右节点。如果为flag为true,访问该节点。