|
| 1 | +class TreeNode { |
| 2 | + constructor(val, left, right) { |
| 3 | + this.val = (val === undefined ? 0 : val); |
| 4 | + this.left = (left === undefined ? null : left); |
| 5 | + this.right = (right === undefined ? null : right); |
| 6 | + } |
| 7 | +} |
| 8 | + |
| 9 | + |
| 10 | +/** |
| 11 | + * @param {TreeNode} root |
| 12 | + * @return {number} |
| 13 | + */ |
| 14 | +function maxPathSum(root) { |
| 15 | + let queue = [root], max = root.val; |
| 16 | + |
| 17 | + const exploreToFindMax = (node) => { |
| 18 | + if (node === null) return; |
| 19 | + console.log(`-> v:${node.val}`) |
| 20 | + |
| 21 | + // let l = node.left, r = node.right; |
| 22 | + // if (l !== null) {} |
| 23 | + const defaultForNull = -Infinity; |
| 24 | + |
| 25 | + let treeLeftVal = 0, exploreLeftVal = defaultForNull; |
| 26 | + if (node.left !== null) { |
| 27 | + treeLeftVal = node.left.val; |
| 28 | + // console.log("exploreToFindMax -> l") |
| 29 | + exploreLeftVal = node.val + exploreToFindMax(node.left); |
| 30 | + } |
| 31 | + // console.log("treeLeftVal") |
| 32 | + // console.log(treeLeftVal) |
| 33 | + // console.log("exploreLeftVal") |
| 34 | + // console.log(exploreLeftVal) |
| 35 | + |
| 36 | + let treeRightVal = 0, exploreRightVal = defaultForNull; |
| 37 | + if (node.right !== null) { |
| 38 | + treeRightVal = node.right.val; |
| 39 | + console.log("exploreToFindMax -> r") |
| 40 | + exploreRightVal = node.val + exploreToFindMax(node.right); |
| 41 | + console.log("exploreRightVal") |
| 42 | + console.log(exploreRightVal) |
| 43 | + } |
| 44 | + |
| 45 | + let treeMax = node.val + treeLeftVal + treeRightVal; // 0 represents not picking any of them |
| 46 | + |
| 47 | + max = Math.max(max, treeMax, exploreLeftVal, exploreRightVal); |
| 48 | + console.log("node.val") |
| 49 | + console.log(node.val) |
| 50 | + console.log("node.val + Math.max(exploreLeftVal, exploreRightVal, 0)") |
| 51 | + console.log(node.val + Math.max(exploreLeftVal, exploreRightVal, 0)) |
| 52 | + return node.val + Math.max(exploreLeftVal, exploreRightVal, 0); |
| 53 | + }; |
| 54 | + |
| 55 | + while (queue.length > 0) { |
| 56 | + let curr = queue.shift(), left = curr.left, right = curr.right; |
| 57 | + if (left !== null) queue.push(left); |
| 58 | + if (right !== null) queue.push(right); |
| 59 | + exploreToFindMax(curr); |
| 60 | + } |
| 61 | + |
| 62 | + console.log("max") |
| 63 | + console.log(max) |
| 64 | + return max; |
| 65 | +} |
| 66 | + |
| 67 | +maxPathSum( |
| 68 | + new TreeNode(1, |
| 69 | + new TreeNode(-2), |
| 70 | + new TreeNode(3) |
| 71 | + ) |
| 72 | +) |
0 commit comments