bool hasPathSumHelper(TreeNode *root, int sum){ //case(1) a leaf if (root ->left == NULL && root->right == NULL) { if (sum == root->val) { return true; }else{ return false; } } //case(2) not a leaf if (root->left !=NULL && hasPathSumHelper(root->left,sum - root->val)) return true; if (root->right !=NULL && hasPathSumHelper(root->right,sum - root->val)) return true; return false; }
//Find if the BST has a path of a particular sum bool BST::hasPathSum(int sum){ if(root == NULL){ cout<<endl<<"Empty tree"<<endl; return sum==0; } else{ return hasPathSumHelper(root,sum); } }
bool hasPathSum(TreeNode *root, int sum) { if(root==NULL) return false; return hasPathSumHelper(root, sum); }