二叉树遍历的非递归写法(伪代码)

stack<Binary>s;
Binary pointer = root;
//前序遍历的非递归写法
s.push(null);
while(!s.empty()) {//或者pointer
	visit(pointer->value);
	if(pointer->right) s.push(pointer->right);
	else if (pointer->left) visit(pointer->left);
	else{
		pointer = s.top();
		s.pop();
	}
}
//中序遍历的非递归写法
stack<Binary>s;
Binary pointer = root;
while(!s.empty() || pointer) {
    if(pointer){
    	s.push(pointer);
    	pointer = pointer->left;
    }else{
    	pointer = s.top();
    	s.pop();
    	visit(pointer);
    	pointer = pointer->right;
    }
}
//后序遍历的非递归算法
struct StackElement
{
	Binary pointer;//二叉树结点
	Type tag;//标签位
};
stack<StackElement>s;
StackElement element;//栈节点
Binary pointer = root;//二叉树节点
while(!s.empty() || pointer) {
    while(pointer) {
        element.pointer = pointer;element.tag = left;
        s.push(element);
        pointer = pointer->left;
    }
    element = s.top();s.pop();
    pointer = element.pointer;
    if (element.tag == left)//从左边结束的
    {
    	element.tag = right;s.push(element);
    	pointer = pointer->right;
    }else{
    	visit(pointer->value);
    	pointer = null;
    }
}

    原文作者:如雨星空
    原文地址: https://blog.csdn.net/xxiaobaib/article/details/78746977
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞