-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path124. Binary Tree Maximum Path Sum (DFS) 20.4.20 Hard
More file actions
95 lines (79 loc) · 3.05 KB
/
124. Binary Tree Maximum Path Sum (DFS) 20.4.20 Hard
File metadata and controls
95 lines (79 loc) · 3.05 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree
along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
Solution: ----------------------------------- DFS ----------------------- https://www.youtube.com/watch?v=9ZNky1wqNUw
--------------------------------------- O(n) T, O(n) S
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
self.res = -float('inf')
self.dfs(root)
return self.res
def dfs(self, currnode): # For a tree, certainly we need to use recursion(DFS or BFS)
if not currnode:
return 0
leftsum = max(0, self.dfs(currnode.left)) # Classic DFS.
# IMPORTANT !!!!! We must compare the value with 0 and take the bigger one
# Because if the leftsum is smaller than 0, we rather not take it into the path
rightsum = max(0, self.dfs(currnode.right))
currsum = leftsum + rightsum + currnode.val # The time complexity is O(n) because we just take every node for consideration
# The current maximum can take both the left and right substree value (闭环)
self.res = max(self.res, currsum)
return currnode.val + max(leftsum, rightsum) # However, for passing the value to upper recursion,
# we can only take the larger one of the left or right substree value
# because the sub-闭环 cannot be a part of a bigger path
Java Version:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int maxSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root);
return maxSum;
}
public int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int leftSum = Math.max(0, dfs(root.left));
int rightSum = Math.max(0, dfs(root.right));
int currSum = root.val + leftSum + rightSum;
maxSum = Math.max(maxSum, currSum);
return Math.max(root.val + leftSum, root.val + rightSum);
}
}