Printing paths in a Binary Tree from root to leaves but the paths are not printing,
Paths in a Binary Search Tree from root to leaves
1
/ \
2 3
/ \ / \
4 5 6 7
/
8
.why is this problem coming please try to give me the solution.
#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;
}
Printing paths in a Binary Tree from root to leaves but the paths are not printing, why is this problem? Printing paths in a Binary Tree from root to leaves but the paths are not printing, why is this problem?
Aucun commentaire:
Enregistrer un commentaire