英文:
no viable conversion from 'TreeNode' to 'TreeNode* '
问题
我无法运行此代码,但根据您提供的代码片段,以下是翻译的部分:
我无法弄清楚这段代码有什么问题。当我运行它时,我得到了这个错误消息:
"error: no viable conversion from 'TreeNode' to 'TreeNode *'
std::cout << s.preorderTraversal(t) << std::endl;"
#include<iostream>
#include<stack>
#include<vector>
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x): val(x), left(NULL), right(NULL){}
};
class Solution {
public:
std::vector<int> preorderTraversal(TreeNode* root)
{
std::vector<int> res;
std::stack<TreeNode*> s;
s.push(root);
while(!s.empty())
{
TreeNode* top = s.top();
s.pop();
if(!top)
res.emplace_back(top->val);
s.push(top->right);
s.push(top->left);
}
return res;
}
};
int main()
{
Solution s;
TreeNode t(1);
std::cout << s.preorderTraversal(t) << std::endl;
}
请注意,我已将代码中的<
和>
替换为了实际的尖括号,以使代码更易读。
英文:
i can't figure out what's wrong with this code. when i run it, i got this error message
"error: no viable conversion from 'TreeNode' to 'TreeNode *'
std::cout << s.preorderTraversal(t) << std::endl;"
#include<iostream>
#include<stack>
#include<vector>
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x): val(x), left(NULL), right(NULL){}
};
class Solution {
public:
std::vector<int> preorderTraversal(TreeNode* root)
{
std::vector<int> res;
std::stack<TreeNode*> s;
s.push(root);
while(!s.empty())
{
TreeNode* top = s.top();
s.pop();
if(!top)
res.__emplace_back(top->val);
s.push(top->right);
s.push(top->left);
}
return res;
}
};
int main()
{
Solution s;
TreeNode t(1);
std::cout << s.preorderTraversal(t) << std::endl;
}
答案1
得分: 1
t
不是一个TreeNode*
指针,这与preorderTraversal()
所期望的不符。
要么将t
声明为指针:
TreeNode * t = new TreeNode(1);
std::cout << s.preorderTraversal(t) << std::endl;
...
delete t;
要么将t
作为指针传递给preorderTraversal()
:
TreeNode t(1);
std::cout << s.preorderTraversal(&t) << std::endl;
要么更改preorderTraversal()
的定义,以接受非指针参数:
std::vector<int> preorderTraversal(TreeNode& root)
...
TreeNode t(1);
std::cout << s.preorderTraversal(t) << std::endl;
这是为了解决您的编译问题。下一个问题将涉及尝试打印一个std::vector
。您应该阅读这个链接。
英文:
t
is not a TreeNode*
pointer, as expected by preorderTraversal()
.
Either declare t
as a pointer:
TreeNode * t = new TreeNode(1);
std::cout << s.preorderTraversal(t) << std::endl;
...
delete t;
Or pass t
as a pointer to preorderTraversal()
:
TreeNode t(1);
std::cout << s.preorderTraversal(&t) << std::endl;
Or change the definition of preorderTraversal()
to accept a non-pointer parameter:
std::vector<int> preorderTraversal(TreeNode& root)
...
TreeNode t(1);
std::cout << s.preorderTraversal(t) << std::endl;
This is for your compilation problem. The next problem will be about trying to print a std::vector
. You should read this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论