forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjdy8739.js
More file actions
36 lines (29 loc) Β· 984 Bytes
/
jdy8739.js
File metadata and controls
36 lines (29 loc) Β· 984 Bytes
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
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxPathSum = function(root) {
let max = root.val;
const dfs = (node) => {
if (!node) {
return 0;
}
const left = Math.max(dfs(node.left), 0);
const right = Math.max(dfs(node.right), 0);
const sum = node.val + left + right;
max = Math.max(sum, max);
return node.val + Math.max(left, right);
}
dfs(root);
return max;
};
// μκ°λ³΅μ‘λ O(n) -> νΈλ¦¬μ λͺ¨λ λ
Έλλ₯Ό μ¬κ·μ μΌλ‘ νμνλ―λ‘ λ³΅μ‘λλ λ
Έλμ μμ λΉλ‘ν¨
// 곡κ°λ³΅μ‘λ O(h) -> μ
λ ₯λ νΈλ¦¬μ μ΅λ λμ΄λ§νΌ μ¬κ· μ€νμ΄ μμ΄λ―λ‘ κ³΅κ°λ³΅μ‘λλ νΈλ¦¬μ λμ΄μ κ°μ