int has_path_sum(bst *b, int sum) { if(b==NULL) return 0; if(!b->left && !b->right) return b->val == sum; return has_path_sum(b->left,sum-b->val) || has_path_sum(b->right,sum-b->val); }
int has_path_sum(struct TreeNode* t, int sum, int target) { if(t == NULL) { return false; } sum += t->val; if(t->left == NULL && t->right == NULL) { if(sum == target) { return true; } else { return false; } } return has_path_sum(t->left, sum, target) || has_path_sum(t->right, sum, target); }
int main() { char ch; int ele; struct node *root = NULL; int num; int depth = 0; int ret; while(1) { printf ("I/i to insert\n"); printf ("P/p to print\n"); printf ("C/c to count\n"); printf ("D/d to max_depth\n"); scanf (" %c", &ch); switch(ch) { case 'i': case 'I': printf ("enter ele\n"); scanf("%d", &ele); root = insert(root, ele); break; case 'p': case 'P': print_tree(root); break; case 'c': case 'C': num = size(root); printf ("number of nodes = %d\n", num); break; case 'd': depth = max_depth(root); printf ("max depth is %d\n", depth); break; case 's': ret = has_path_sum (root, 10); if (ret == FOUND) printf ("found\n"); else if (ret == NOT_FOUND) printf ("not found \n"); else printf ("unknown\n"); break; case 't': print_paths (root); break; default: printf ("pls provide proper input\n"); } } }
bool has_path_sum(tree_node* T, int sum) { /* Given a tree and a sum, return true if there is a path from the root down to a leaf, such that adding up all the values along the path equals the given sum. Strategy: subtract the node value from the sum when recurring down, and check to see if the sum is 0 when you run out of tree. */ bool l_has = false; bool r_has = false; if(T!=NULL) { if((T->data == sum) &&(T->left == NULL) &&(T->right == NULL)) return true; l_has = has_path_sum(T->left, sum - T->data); r_has = has_path_sum(T->right, sum - T->data); } return l_has || r_has; }
int has_path_sum (struct node *node, int sum) { int ret = NOT_FOUND; if (!node) return; else if (!(node->left) && !(node->right)) { sum = sum - node->ele; if (!sum) return FOUND; else return NOT_FOUND; } else { ret = ret || has_path_sum(node->left, (sum - (node->ele))); ret = ret || has_path_sum (node->right, (sum - (node->ele))); } return ret; }
bool hasPathSum(struct TreeNode* root, int sum) { return has_path_sum(root, 0, sum); }