微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

修改后栈顶元素保持不变

如何解决修改后栈顶元素保持不变

我正在尝试修改函数 preorderTraversal 中堆栈 stk 顶部元素的状态字段,但是该字段似乎不会随时更改为 2 并且一直在 0 和 1 之间切换。谢谢。

这就是算法应该如何工作 -
如果栈顶元素的状态为 0 ,则在欧拉遍历中第一次访问节点(预排序) 如果栈顶元素的状态为 1 ,则在欧拉遍历中第二次访问节点(中序) 如果栈顶元素的状态为 2 ,则在欧拉遍历中第三次访问节点(后序)。

我通过修改堆栈顶部的状态字段并相应地将树的前序、中序和后序插入向量中来跟踪状态。

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0),left(nullptr),right(nullptr) {}
    TreeNode(int x) : val(x),right(nullptr) {}
    TreeNode(int x,TreeNode *left,TreeNode *right) : val(x),left(left),right(right) {}
};
class pairr
{
public:
    TreeNode *node;
    int status;
    pairr(TreeNode *root,int status)
    {
        this->node = root;
        this->status = status;
    }
};
vector<int> preorderTraversal(TreeNode *root)  
{
    stack<pairr> stk; 
    vector<vector<int>> ans(3,vector<int>());   //ans[0 to 2] stores pre,in and postorder respectively . 
    stk.push(pairr(root,0));
    while (stk.empty() != true)
    {
        pairr temp = stk.top();
        if (temp.status == 0)                   //if status is 0,in Euler traversal node is visited for the first time,so increase status to 1(preorder)
        {
            if (temp.node != NULL)
            {
                ans[0].push_back(temp.node->val);
                if (temp.node->left)
                {
                    stk.push(pairr(temp.node->left,0));
                }
            }
            temp.status += 1;
        }
        else if (temp.status == 1) //if status is 1,in Euler traversal node is visited for the second time,so increase status to 2(Inorder)
        {
            if (temp.node != NULL)
            {
                ans[1].push_back(temp.node->val);
                if (temp.node->right)
                {
                    stk.push(pairr(temp.node->right,0));
                }
            }
            temp.status = 2;
        }
        else //if status is 2,in Euler traversal node is visited for the third time,so add to vector and pop (Post order)
        {
            if (temp.node != NULL)
                ans[2].push_back(temp.node->val);
            stk.pop();
        }
    }
    return ans[0];
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。