1
+ ///
2
+ /// Problem: Binary Tree Maximum Path Sum
3
+ ///
4
+ /// A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the
5
+ /// sequence has an edge connecting them. A node can only appear in the sequence at most once.
6
+ /// Note that the path does not need to pass through the root.
7
+ ///
8
+ /// The path sum of a path is the sum of the node's values in the path.
9
+ ///
10
+ /// Given the root of a binary tree, return the maximum path sum of any non-empty path.
11
+ ///
12
+ /// Example 1:
13
+ /// Input: root = [1,2,3]
14
+ /// Output: 6
15
+ /// Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
16
+ ///
17
+ /// Example 2:
18
+ /// Input: root = [-10,9,20,null,null,15,7]
19
+ /// Output: 42
20
+ /// Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
21
+ ///
22
+ /// Constraints:
23
+ /// The number of nodes in the tree is in the range [1, 3 * 10^4].
24
+ /// -1000 <= Node.val <= 1000
25
+ ///
26
+
27
+ // Definition for a binary tree node (provided by LeetCode)
28
+ // #[derive(Debug, PartialEq, Eq)]
29
+ // pub struct TreeNode {
30
+ // pub val: i32,
31
+ // pub left: Option<Rc<RefCell<TreeNode>>>,
32
+ // pub right: Option<Rc<RefCell<TreeNode>>>,
33
+ // }
34
+ //
35
+ // impl TreeNode {
36
+ // #[inline]
37
+ // pub fn new(val: i32) -> Self {
38
+ // TreeNode {
39
+ // val,
40
+ // left: None,
41
+ // right: None
42
+ // }
43
+ // }
44
+ // }
45
+
46
+ // # Solution
47
+ // Time complexity: O(n)
48
+ // Space complexity: O(h) - Where h is the height of the tree
49
+
50
+ use std:: rc:: Rc ;
51
+ use std:: cell:: RefCell ;
52
+ use std:: cmp;
53
+ impl Solution {
54
+ pub fn max_path_sum ( root : Option < Rc < RefCell < TreeNode > > > ) -> i32 {
55
+ let mut max_sum = std:: i32:: MIN ;
56
+ Self :: max_gain ( root, & mut max_sum) ;
57
+ max_sum
58
+ }
59
+
60
+
61
+ fn max_gain ( node : Option < Rc < RefCell < TreeNode > > > , max_sum : & mut i32 ) -> i32 {
62
+ if let Some ( n) = node {
63
+ let node_ref = n. borrow ( ) ;
64
+
65
+ let left_gain = cmp:: max ( 0 , Self :: max_gain ( node_ref. left . clone ( ) , max_sum) ) ;
66
+ let right_gain = cmp:: max ( 0 , Self :: max_gain ( node_ref. right . clone ( ) , max_sum) ) ;
67
+
68
+ let price_new_path = node_ref. val + left_gain + right_gain;
69
+
70
+ * max_sum = cmp:: max ( * max_sum, price_new_path) ;
71
+
72
+ node_ref. val + cmp:: max ( left_gain, right_gain)
73
+ } else {
74
+ 0
75
+ }
76
+ }
77
+ }
0 commit comments