C++ 输出不打印?
打印二叉树中从根到叶的路径,但这些路径不打印C++ 输出不打印?,c++,c++11,c++14,C++,C++11,C++14,打印二叉树中从根到叶的路径,但这些路径不打印 Paths in a Binary Search Tree from root to leaves 1 / \ 2 3 / \ / \ 4 5 6 7 / 8 1.这个问题为什么会出现请给我一个解决办法 #include<bits/stdc++.h> #include <stdio.h>
Paths in a Binary Search Tree from root to leaves
1
/ \
2 3
/ \ / \
4 5 6 7
/
8
1.这个问题为什么会出现请给我一个解决办法
#include<bits/stdc++.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
bool flag = true;
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
list<string> getPath(Node *root, list<string> l, string s)
{
// Base Case
if (root==NULL)
return l;
if(root->left == NULL && root->right== NULL) {
if(!flag) {
s=s+"->";
}
s=s + to_string(root->data);
l.push_back(s);
}
else {
if(!flag) {
s=s+"->";
}
s=s + to_string(root->data);
}
flag = false;
if(root->left != NULL) {
getPath (root->left,l,s);
}
if(root->right != NULL) {
getPath (root->right,l,s);
}
return l;
}
list<string> binaryTreePaths(Node * root)
{
string s="";
list<string> l;
return getPath(root, l, s);
}
//function for printing the elements in a list
void showlist(list <string> g)
{
list <string> :: iterator it;
for(it = g.begin(); it != g.end(); ++it)
cout << '\t' << *it;
cout << '\n';
}
int main()
{
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->right = newNode(8);
printf("Paths of this Binary Tree are:\n");
list<string> s=binaryTreePaths(root);
showlist(s);
getchar();
return 0;
}
从二进制到二进制的打印路径,但路径不打印,为什么会出现这个问题?
< p>在C++中有一个非常基本的事实:参数是由值传递的,并且修改函数内的参数不会修改函数范围之外的参数。如果你想在递归过程中修改L和S,你需要声明它们为引用,用C++表示。因此,为了使程序输出有意义,您需要做的唯一更改是将l声明为引用list<string> getPath(Node *root, list<string>& l, string s)
输出:
此二叉树的路径为:
1->2->4->81->2->51->3->61->3->7你试过调试它吗?我想看看您对getpath的递归调用。停止使用它!不包含,这是一个私有的非标准标题,不用于包含。为什么包含C标题?那么我应该如何使用它@tambreYes我错过了推荐人的概念,谢谢你的帮助。事实上,我期待的是1->2->4->8,1->2->5,1->3->6,1->3->7。当在本地代码块中运行相同的代码时,我得到了一个错误,为什么会发生这种情况@什么是错误?它在我的VisualStudio上工作,虽然这可能不是一个很有代表性的编译器。它显示给_string not identified@leyanpanThis实际上是一个来自