sum path in the tree

/***
4.9
You are given a binary tree in which node contains a value. Design an algorithm
to print all paths which which sums to given value. Note that a path can start or
end anywhere in the tree.
complexity O(n^2)
***/

#include<iostream>
#include<vector>

using namespace std;

struct node {
       int val;
       node *left, *right;
};

class sumpath {
public:
       sumpath(int sum);
       ~sumpath() {}
       void path(node *root);
       void print();
private:
       int givenSum;
       node *root;
       vector<vector<int>> paths;
       void getpath(node *n, int sum, vector<int> *path);
};

sumpath::sumpath(int sum) {
       this->givenSum = sum;
}

void sumpath::getpath(node *n, int sum, vector<int> *path) {
       if(n == nullptr) return;

       sum = sum + n->val;
       if(sum == givenSum) {
              path->push_back(n->val);
              paths.push_back(*path);
              path->pop_back();
       }
       else if(sum < givenSum) {
              path->push_back(n->val);
       } else return;

       getpath(n->left, sum, path);
       getpath(n->right, sum, path);
}

void sumpath::path(node *root) {
       if(root == nullptr) return;

       vector<int> mypath;
       getpath(root, 0,  &mypath);

       path(root->left);
       path(root->right);
}

void sumpath::print() {
       if(paths.empty())
              cout<<"no proper path"<<endl;
       else {
              for(int i=0; i<paths.size(); i++) {
                     for (int j=0; j<paths[i].size(); j++)
                     {
                           cout<<paths[i][j]<<"->";
                     }
                     cout<<endl;
              }
       }     
}

void main() {
       node n[7];
       for(int i=0; i<7; i++) {
              n[i].val = i+1;
              n[i].left = nullptr;
              n[i].right = nullptr;
       }

       n[0].left = n+3;
       n[0].right = n+5;
       n[3].left = n+4;
       n[3].right = n+1;
       n[5].left = n+2;
       n[5].right = n+6;

       sumpath sp(9);
       sp.path(n);
       sp.print();

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs