I wrote the following function to find out the minimum sum of any path in a Binary Search Tree:
int minSumPath(TreeNode* root) {
if(root==NULL)
return 0;
int sum = root->value;
if(root->left!=NULL && root->right!=NULL)
sum += min(minSumPath(root->left),minSumPath(root->right));
else
if(root->left==NULL)
sum += minSumPath(root->right);
else
sum += minSumPath(root->left);
return sum;
}
While the above code generates the correct output, I feel that I am not leveraging the fact that it is a Binary Search Tree (BST) and not just a Binary Tree.
In a BST the left child node is smaller than the root and right node, so logically we can only consider the left child nodes of each root; but what if the BST has only a single child on the right (with say value 10) and multiple child nodes on the left (with sum >10)?
In this case the minimum sum would be 10 (which is on the right).
How I would be able to leverage the BST property, if at all? Also, any other optimizations that I can use in my approach?
Note: Edited the code to resolve the error;