-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay39.cpp
More file actions
62 lines (47 loc) · 1.03 KB
/
Day39.cpp
File metadata and controls
62 lines (47 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
This question was asked by Apple.
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 sum 15.
10
/ \
5 5
\ \
2 1
/
-1
*/
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node *left;
Node *right;
Node(int val) : val(val), left(nullptr), right(nullptr) {}
};
int minPathSum(Node *root)
{
if (root == nullptr)
{
return INT_MAX;
}
if (root->left == nullptr and root->right == nullptr)
{
return root->val;
}
int left = minPathSum(root->left);
int right = minPathSum(root->right);
int ans = root->val + min(left, right);
return ans;
}
int main()
{
Node *root = new Node(10);
root->left = new Node(5);
root->right = new Node(5);
root->left->right = new Node(2);
root->right->right = new Node(1);
root->right->right->left = new Node(-1);
cout << " Minimum Path Sum : " << minPathSum(root) << endl;
return 0;
}