-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreeRootToLeaf.js
More file actions
62 lines (49 loc) · 1.56 KB
/
Copy pathbinaryTreeRootToLeaf.js
File metadata and controls
62 lines (49 loc) · 1.56 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
class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function minPathSum(root) {
if (!root) return 0;
function dfs(node, currentSum) {
// Base case: if it's a leaf node, return the path sum
if (!node.left && !node.right) {
return currentSum + node.val;
}
// Initialize left and right path sums with a large value
let leftSum = Infinity;
let rightSum = Infinity;
// Traverse left and right subtrees if they exist
if (node.left) {
leftSum = dfs(node.left, currentSum + node.val);
}
if (node.right) {
rightSum = dfs(node.right, currentSum + node.val);
}
// Return the minimum of the left and right path sums
return Math.min(leftSum, rightSum);
}
// Start DFS traversal from the root with an initial sum of 0
return dfs(root, 0);
}
// Construct the example tree
let 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);
// Call the function and print the minimum path sum
console.log(minPathSum(root)); // Output: 15