二叉树前序中序后序的非递归遍历

1前序遍历

按照根左右的顺序进行遍历,首先访问根节点,若左孩子非空,访问左子树;右孩子非空访问右子树。以此规则遍历整个二叉树

(1)当前点入栈,输出该节点

(2)如当前节点左孩子非空,访问该节点的左孩子回到(1)

(3)若当前节点左孩子为空,访问该节点右孩子回到(1)

    stack<TreeNode*>s;
	vector<int> res;
    TreeNode *p=root;
	while(p!=NULL||!s.empty())
	{
	    while(p)
	    {
	        res.push_back(p->val);
	        s.push(p);
	        p=p->left;
	    }
	    if(!s.empty())
	    {
	        p=s.top();
	        s.pop();
	        p=p->right;
	    }
	}

2中序遍历

和前序遍历思路一样,只不过当左孩子为空才访问当前节点

(1)当前点入栈

(2)如当前节点左孩子非空,访问该节点的左孩子回到(1)

(3)若当前节点左孩子为空,输出该节点并访问该节点右孩子回到(1)

stack<TreeNode*>s;
	vector<int> res;
    TreeNode *p=root;
	while(p!=NULL||!s.empty())
	{
	    while(p)
	    {
	        s.push(p);
	        p=p->left;
	    }
	    if(!s.empty())
	    {
	        p=s.top();
	        respush_back(p->val);
	        s.pop();
	        p=p->right;
	    }
	}

3后序遍历

按照左右根的顺序遍历二叉树,对于任一节点,若无左右孩子或者左右孩子均已访问,才可输出。同时为保证先输出左孩子,应先处理右子树。

stack<TreeNode*>s;
	vector<int> res;
    TreeNode *p=root;
	TreeNode *pre=NULL;     //前一节点
	while(!s.empty())
	{
	    p=s.top();
	    if((p->left==NULL&&p->right==NULL)||(pre!=NULL&&(pre==p->left||pre==p->right)))
	    {
	        res.push_back(p->val);
	        s.pop();
	        pre=p;
	    }
	    else
	    {
	        if(p->right) p=p->right;
	        if(p->left) p=p->left;
	    }
	}

猜你喜欢

转载自blog.csdn.net/baidu_38812770/article/details/81196785