|
| 1 | +/********************************************************** |
| 2 | + |
| 3 | + Following is the Binary Tree Node class structure |
| 4 | + |
| 5 | + template <typename T> |
| 6 | + class BinaryTreeNode { |
| 7 | + public : |
| 8 | + T data; |
| 9 | + BinaryTreeNode<T> *left; |
| 10 | + BinaryTreeNode<T> *right; |
| 11 | + |
| 12 | + BinaryTreeNode(T data) { |
| 13 | + this -> data = data; |
| 14 | + left = NULL; |
| 15 | + right = NULL; |
| 16 | + } |
| 17 | + }; |
| 18 | + |
| 19 | +***********************************************************/ |
| 20 | +void helper(BinaryTreeNode<int>* root,int k,vector<int> ans){ |
| 21 | + if(root==NULL){ |
| 22 | + return; |
| 23 | + } |
| 24 | + if(root->left==NULL&&root->right==NULL&&k==root->data){ |
| 25 | + ans.push_back(root->data); |
| 26 | + for(int i=0;i<ans.size();i++){ |
| 27 | + cout<<ans[i]<<" "; |
| 28 | + } |
| 29 | + cout<<endl; |
| 30 | + return; |
| 31 | + } |
| 32 | + if(root->left==NULL&&root->right==NULL&&k!=root->data){ |
| 33 | + return; // no need for pop_back as every function i.e every recursive call |
| 34 | + //has it's own static vector. |
| 35 | + } |
| 36 | + ans.push_back(root->data); |
| 37 | + helper(root->left,k-root->data,ans); |
| 38 | + helper(root->right,k-root->data,ans); |
| 39 | +} |
| 40 | +void rootToLeafPathsSumToK(BinaryTreeNode<int> *root, int k) { |
| 41 | + vector<int> v; |
| 42 | + helper(root,k,v); |
| 43 | +} |
0 commit comments