How to find the minimum path sum in a binary tree, and print the path? The path can be from ROOT node to any LEAF node. I have written the C++ code to find the min sum, but have problems in printing the path.
int MinTreePathSum(TreeNode *head, vector<TreeNode> &path)
{
if(!head) // head is NULL
return 0;
else if(!(head->left) && head->right) // only head->left is NULL
return head->val+MinTreePathSum(head->right, path);
else if(!(head->right) && head->left) // only head->right is NULL
return head->val+MinTreePathSum(head->left, path);
else
return head->val+min(MinTreePathSum(head->left, path), MinTreePathSum(head->right, path)); // none of left and right are NULL
}
The path
in the argument list is not used, could anyone help me to print the path which has the minimum path sum?
vector<TreeNode>
instead ofvector<TreeNode*>
? – Christophepath
vector is initially with size = 0, it is used to store the qualifiedTreeNode
. 2) I think we can do either way, as long as the path is uniquely determined. – Liang Livector<TreeNode *>
is much better thanvector<TreeNode>
. Forget about my previous answer 2) – Liang Li