二叉树非递归前序遍历

题目描述

给你二叉树的根节点root,返回前序遍历

输入:root = [1,null,2,3]
输出:[1,2,3]

方法1:探路指针版[[二叉树非递归中序遍历#^0ff251]] ^ea08fd

class Solution
{
	public:
	vector<int> preorderTraversal(TreeNode* root)
	{
		vector<int> res; //储存答案
		stack<TreeNode*> sta; //储存节点的栈
		TreeNode* n=root;
		while(!sta.empty() || n) //因为探路指针不空则说明还有点没有遍历到
		{
			while(n)//该点不为空指针,则为符合要求的节点,持续入栈,这相当于是深搜一直往左搜
			{
				res.push_back(n->val);
				sta.push(n);
				n=n->left;//接着往左搜
			}
			//直到左边为空,回头
			n=sta.top();sta.pop();
			n=n->right;//然后没有办法,伸向右子树
		}
		return res;
	}
};

事实上我们可以看到这个版本很好理解:

  • 第一层while(n)代表一直往左走,走到底
  • 第二层代表前序遍历在第一点失败后迫不得已往右走
  • 注意一下while循环的出口条件就可以了

版本2:万能标记法 ^329f4c

typedef pair<int,TreeNode*> IT;
class Solution {
public:
    vector<int> pretorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<IT> sta;
        sta.push({0,root});
        while(!sta.empty())
        {
            auto u=sta.top();
            int flag=u.first;
            sta.pop();
            TreeNode* node=u.second;
            if(!node) continue;
            if(!flag)
            {
	            //只需要明确前序是根节点在前面输出,而node的位置代表根节点
                sta.push({0,node->right});
                sta.push({0,node->left});
                sta.push({1,node});
            }
            else res.push_back(node->val);
        }
        return res;
    }
};

说明:

  • 虽然重复入栈,但是显然十分易懂
posted @ 2022-11-13 23:50  绊缘  阅读(20)  评论(0)    收藏  举报