二叉树非递归中序遍历

题目描述:给定一个二叉树的根节点root,返回它的中序遍历
![inorder_1.jpg (202×324) (leetcode.com)

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

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

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

方法2: 万能标记版[[二叉树非递归前序遍历#^329f4c]]

typedef pair<int,TreeNode*> IT;
class Solution {
public:
    vector<int> inorderTraversal(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)
            {
	            //只需要自下往上按照x序遍历的顺序写就可以了
                sta.push({0,node->right});
                sta.push({1,node});
                sta.push({0,node->left});
            }
            else res.push_back(node->val);
        }
        return res;
    }
};
posted @ 2022-11-13 23:49  绊缘  阅读(7)  评论(0)    收藏  举报