Traverse all paths of a given binary search tree.
Only thing is we need to do is some book keeping so that we can print the path when we reach a leaf node.
print only those paths which sums up to a given number
Only thing is we need to do is some book keeping so that we can print the path when we reach a leaf node.
void printPath2(Node * node, int path[], int pathLen){int i;if(!node)return;path[pathLen] = node->value;int isLeaf = node->left == NULL && node->right == NULL;if(isLeaf ){for(i=0; i<=pathLen; i++)printf("%d, ", path[i]);printf("\n");}printPath2(node->left, path, pathLen+1);printPath2(node->right, path, pathLen+1);return ;}
print only those paths which sums up to a given number
Find whether a tree contains a path with given sumvoid printPath(Node * node, int sum, int path[], int pathLen){if(node == NULL){return;}int subSum = sum - node->value;path[pathLen] = node->value;int isLeaf = node->left == NULL && node->right == NULL;if(isLeaf && subSum ==0){for(i=0; i<=pathLen; i++)printf("%d, ", path[i]);printf("\n");}printPath(node->left, subSum, path, pathLen+1);printPath(node->right, subSum, path, pathLen+1);return ;}
Read full article from Algorithms and Me: Paths in a Binary Search Treeint hasPath(Node * node, int sum){int lpath, rpath;if(node == NULL)return sum == 0;int subSum = sum - node->value;if(node->left == NULL && node->right == NULL)return subSum == 0;if(node->left)lpath = hasPath(node->left, subSum);if(node->right)rpath = hasPath(node->right, subSum);return rpath || lpath;}