forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforest000014.java
More file actions
50 lines (45 loc) ยท 2.09 KB
/
forest000014.java
File metadata and controls
50 lines (45 loc) ยท 2.09 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
/*
# Time Complexity: O(n)
# Space Complexity: O(n)
- ์ฌ๊ท ํธ์ถ ๋ด๋ถ์์ left, right ๋ณ์๋ฅผ ์ฌ์ฉํ๊ณ , ์ฌ๊ท ํธ์ถ ์ต๋ ๊น์ด๋ n์ด๋ฏ๋ก
# Solution
์ ์ฒด ๋ฌธ์ ๋ฅผ ๊ฐ subtree์ ๋ํ ๋ฌธ์ ๋ก ์ชผ๊ฐ์ด ์๊ฐํ ์ ์์ต๋๋ค.
์์์ ๋
ธ๋ x์ ๋ํด, x์ ์ผ์ชฝ ์์์ x_l, x์ ์ค๋ฅธ์ชฝ ์์์ x_r, x์ ๊ฐ์ x.val์ด๋ผ๊ณ ์ ์ํ๊ฒ ์ต๋๋ค.
x๋ฅผ root๋ก ํ๋ subtree์์ 'x๋ฅผ path์ ํ์ชฝ ๋์ผ๋ก ํ๋ path sum ์ค ์ต๋๊ฐ'์ dp[x]๋ผ๊ณ ์ ์ํ๊ฒ ์ต๋๋ค.
๊ทธ๋ฌ๋ฉด dp[x] = max(max(0, dp[x_l]) + x.val, max(0, dp[x_r]) + x.val) ๋ก ๊ตฌํ ์ ์์ต๋๋ค. (subtree์ dp ๊ฐ์ด ์์์ธ ๊ฒฝ์ฐ๋ ๋ฒ๋ฆฌ๋ฉด ๋๊ธฐ ๋๋ฌธ์.)
์ด์ root๋ก๋ถํฐ ์ถ๋ฐํด์ DFS๋ก ์ ์ฒด ๋
ธ๋๋ฅผ ์ํํ๋ฉฐ ์ด ์ ํ์์ ์ ์ฉํ๋ฉด, ์ ์ฒด tree์ ๋ํด dp๊ฐ์ ๊ตฌํ ์ ์์ต๋๋ค.
๋จ, ๋ฌธ์ ์์ ์ํ๋ ๋ต์ root๋ฅผ ๋ฐ๋์ path์ ํ์ชฝ ๋์ผ๋ก ์ํ๋ ๊ฒ์ ์๋๊ณ , ์ฌ์ง์ด root๊ฐ path์ ํฌํจ๋์ง ์์๋ ๋๊ธฐ ๋๋ฌธ์,
์ด์ค๊ฐํ(?) (= root๋ฅผ path์ ํฌํจํ์ง ์๋) path๋ ๊ณ ๋ คํ ํ์๊ฐ ์๋๋ฐ์.
์ด๋ฅผ ๊ณ ๋ คํ๊ธฐ ์ํด, ๊ฐ ์ฌ๊ท ํจ์ ํธ์ถ๋ง๋ค max(0, dp[x_l]) + root.val + max(0, dp[x_r]) ๊ฐ์ด ์ ๋ต์ด ๋ ์ ์๋์ง ์ฒดํฌํ๋ ๊ณผ์ ์ด ํ์ํฉ๋๋ค.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int ans = -30_000_001;
public int maxPathSum(TreeNode root) {
maxInTree(root);
return ans;
}
public int maxInTree(TreeNode root) {
if (root == null) {
return 0;
}
int left = Math.max(0, maxInTree(root.left));
int right = Math.max(0, maxInTree(root.right));
ans = Math.max(ans, left + root.val + right);
return root.val + Math.max(left, right);
}
}