Push_back() 没有向向量添加元素? (C++树遍历)
我正在解决树遍历问题,并使用“push_back”向量函数通过有序遍历来更新向量。除了使用它之外,我还使用 cout 打印出要调试的解决方案。打印输出是正确的,但我的返回向量与打印不匹配,所以我只能将其归咎于我不理解 Push_back 函数是如何工作的。
这是我正在使用的函数:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> order {};
if (root != nullptr) {
inorderTraversal(root->left);
cout << "pushing back : " << root->val << std::endl;
order.push_back(root->val);
inorderTraversal(root->right);
}
return order;
}
对于输入树 [1,null,2,3] 我的标准输出正在打印:
推回:1 向后推:3 推回:2
这是正确的,但我返回的数组(顺序)只是 [1]。
I'm working through a tree traversal problem and using 'push_back' vector function to update a vector with the in-order traversal. Alongside using this I am using cout to print out the solution to debug. The print output is correct but my returning vector doesn't match the print so I can only put this down to me not understanding how the push_back function works.
This is the function I am using:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> order {};
if (root != nullptr) {
inorderTraversal(root->left);
cout << "pushing back : " << root->val << std::endl;
order.push_back(root->val);
inorderTraversal(root->right);
}
return order;
}
For the input tree [1,null,2,3] My stdout is printing:
pushing back : 1
pushing back : 3
pushing back : 2
Which is correct but my returning array (order) is only [1].
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您忽略了每次递归的结果。你应该这样做:
更高效
也就是说,如果你计算一下在此创建的本地向量的数量,虽然很短,但它们会很多(与树中的节点一样多,在事实)。您可以通过在实际遍历和顺序向量创建之间提供垫片来消除所有这些中间人向量:
这样做会创建一个向量,并在此过程中消除 (N-1) 个临时向量,其中N 是树中的节点数。
You're ignoring the results from each recursion. You should be doing this:
Much More Efficient
That said, if you counted the number of local vectors created in this, though short, they will be many (as many as there are nodes in your tree, in fact). You can eliminate all of those middle-men vectors by providing a shim between the actual traversal and the creation of the order vector:
Doing this creates a single vector, and in so doing eliminates (N-1) temporary vectors along the way, where N is the number of nodes in the tree.