CPP 程序中未定义的行为

undefined behaviour in cpp program

本文关键字:未定义 程序 CPP      更新时间:2023-10-16

我是 cpp 的新手,我知道我的问题很愚蠢,但除了这里我别无他法,if 块有什么问题,我的逻辑非常正确,但我不知道为什么我的程序因为 if 块而给出 TLE

在线裁判链接 leetcode

当我更改 if 循环时

if((st.empty()==false)&&(st.top()==root)){
root=root->right;
}else{
ans.push_back(root->val);
root=NULL;
}

从下面的程序中挑选,然后运行良好,请帮助我 我是cpp的新手,我之前用python编程请帮忙。 我的 if 块有什么问题

这是我的解决方案正在获得TLE

class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*>st;
vector<int>ans;
while(root||!st.empty()){
while(root){
st.push(root);
st.push(root);
root=root->left;
}
if(st.empty())return ans;
root = st.top();
st.pop();
if((st.empty()==false)&&(st.top()==root)){  //if((st.empty()==false)&&(st.top()==root))
root==root->right;
}else{
ans.push_back(root->val);
root=NULL;
}
}
return ans;
}
};

接受以下解决方案

class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*>st;
vector<int>ans;
while(root||!st.empty()){
while(root){
st.push(root);
st.push(root);
root=root->left;
}
if(st.empty())return ans;
root = st.top();
st.pop();
if((st.empty()==false)&&(st.top()==root)){
root=root->right;
}else{
ans.push_back(root->val);
root=NULL;
}

}
return ans;
}
};

这是错误的:

if((st.empty()==false)&&(st.top()==root)){  //if((st.empty()==false)&&(st.top()==root))
root==root->right;

你不是在分配root,而是在比较它。

修复:

root=root->right;