//
// main.cpp
// Root to leaf path
//
// Created by Himanshu on 08/02/22.
//
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
int val = 0;
struct TreeNode *left, *right;
};
TreeNode* newNode(int data)
{
TreeNode* Node = new TreeNode();
Node->val = data;
Node->left = NULL;
Node->right = NULL;
return(Node);
}
void solve(TreeNode* root, vector<string>& paths, string s) {
if (root == NULL) {
return;
} else {
if (root->left == NULL && root->right == NULL) {
paths.push_back(s + to_string(root->val));
}
solve(root->left, paths, s + to_string(root->val) + "->");
solve(root->right, paths, s + to_string(root->val) + "->");
}
}
int main() {
TreeNode *root = newNode(3);
root->left = newNode(9);
root->right = newNode(20);
root->right->left = newNode(15);
root->right->right = newNode(7);
vector<string> paths;
string s = "";
cout<<"Paths from root to leaf are: "<<endl;
solve(root, paths, s);
for (int i=0; i<paths.size(); i++) {
cout<<paths[i]<<endl;
}
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBSb290IHRvIGxlYWYgcGF0aAovLwovLyAgQ3JlYXRlZCBieSBIaW1hbnNodSBvbiAwOC8wMi8yMi4KLy8KCiNpbmNsdWRlIDxpb3N0cmVhbT4KI2luY2x1ZGUgPHF1ZXVlPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKc3RydWN0IFRyZWVOb2RlIHsKICAgIGludCB2YWwgPSAwOwogICAgc3RydWN0IFRyZWVOb2RlICpsZWZ0LCAqcmlnaHQ7Cn07CgpUcmVlTm9kZSogbmV3Tm9kZShpbnQgZGF0YSkKewogICAgVHJlZU5vZGUqIE5vZGUgPSBuZXcgVHJlZU5vZGUoKTsKICAgIE5vZGUtPnZhbCA9IGRhdGE7CiAgICBOb2RlLT5sZWZ0ID0gTlVMTDsKICAgIE5vZGUtPnJpZ2h0ID0gTlVMTDsKIAogICAgcmV0dXJuKE5vZGUpOwp9CgoKdm9pZCBzb2x2ZShUcmVlTm9kZSogcm9vdCwgdmVjdG9yPHN0cmluZz4mIHBhdGhzLCBzdHJpbmcgcykgewogICA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