Find minimum path sum from root to leaf

Given a binary tree, find a minimum path sum from root to a leaf.

For example, the minimum path in this tree is [10, 5, 1, -1], which has the sum of 15.

Example:

Input:

  10
 /  \
5    5
 \     \
   2    1
       /
     -1
Output: 15

Approach

C++

#include <bits/stdc++.h>
using namespace std;
//struct for treenode
struct TreeNode
{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};
int minPathSum(TreeNode *root)
{
    if (root == NULL)
        return 0;
    int sum = root->data;
    int leftSum = INT_MAX;
    int rightSum = INT_MAX;
    if (root->right == NULL && root->left == NULL)
    {
        return sum;
    }
    else
    {

        if (root->left != NULL)
        {
            leftSum = minPathSum(root->left);
        }
        if (root->right != NULL)
        {
            rightSum = minPathSum(root->right);
        }
        if (leftSum < rightSum)
        {
            sum += leftSum;
        }
        else
        {
            sum += rightSum;
        }
    }

    return sum;
}

int main()
{
    TreeNode *root = new TreeNode(10);
    root->left = new TreeNode(5);
    root->right = new TreeNode(5);
    root->left->right = new TreeNode(2);
    root->right->right = new TreeNode(1);
    root->right->right->left = new TreeNode(-1);

    cout << minPathSum(root);

    return 0;
}


No comments:

Post a Comment