打印路徑不打印,輸出不打印?二叉樹從根到葉,但路徑
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;
}
打印幅面從根到葉,但路徑不打印,爲什麼這個問題呢?
您是否嘗試調試它? 我會看看你的遞歸調用getpath() – Federico
[''使用命名空間標準;'是一個不好的做法](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-認爲壞實踐)。停止使用它! – tambre
不要包含,它是一個私有的非標準頭文件,不包含在內。你爲什麼包含C頭? –
2017-09-02 09:39:03