Tuesday, September 10, 2013

all paths in a tree which sum up to a value

/* From Cracking the Coding Interview 4-8.
You are given a binary tree in which each node contains a value.
 Design an algorithm to print all paths which sum up to that value.
 Note that it can be any path in the tree - it does not have to start at the root. */

/* I use the algorithm suggested in the book for the implementation (with slight improvement). The key point to the algorithm is: On every node, we look “up” to see if we’ve found the sum.
*/

struct node {
    node(int v): value(v), left(nullptr), right(nullptr) { }
    int value;
    node * left, * right;
};

void printPath(vector<int> & v, int i) {
    for (int u = i; u < (int) v.size(); ++u) {
     cout << v[u] << " ";
    }
    cout << endl;
}

void sumInPath(node * n, vector<int> v, const int & sum) {
    if (!n) {
        return;
    }
    v.push_back(n->value);
    int total = 0;
    for (int i = (int) v.size()-1; i >= 0; --i) {
     total += v[i];
     if (total == sum) {
          printPath(v, i);
     }
    }
    if (n->left) {
     sumInPath(n->left, v, sum);
    }
    if (n->right) {
     sumInPath(n->right, v, sum);
    }

}

No comments:

Post a Comment