在二叉树中打印从根到叶的路径,但路径没有打印,
Paths in a Binary Search Tree from root to leaves
1
/ \
2 3
/ \ / \
4 5 6 7
/
8
.为什么会出现这个问题,请尝试给我解决方案。
#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;
}
在二叉树中打印从根到叶的路径,但路径没有打印,为什么会出现这个问题?
C++ 中有一个非常基本的事实,即参数是按值传递的,在函数内部修改参数不会在函数作用域外修改它们。如果要在递归过程中修改 l 和 s,则需要将它们声明为引用,在 C++ 中用 & 表示。因此,为了使程序输出某些内容,您需要进行的唯一更改是将l 声明为引用。
list<string> getPath(Node *root, list<string>& l, string s)
输出:这个二叉树的路径是:1->2->4->8 1->2->5 1->3->6 1->3->7
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句