Timeline
Timeline
2025-10-28
init
DFS
Problem:
Using DFS, the maximum value should be the maximum contribution of the left subtree plus the maximum contribution of the right subtree plus the value of the current node
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 | // Definition for a binary tree node.struct Solution;pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>,}impl TreeNode { pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None, } }}use std::cell::RefCell;use std::cmp::max;use std::rc::Rc;impl Solution { pub fn max_path_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { let mut max_sum = i32::MIN; Self::dfs(&root, &mut max_sum); max_sum } fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, max_sum: &mut i32) -> i32 { if let Some(n) = node { let n = n.borrow(); // The maximum contribution of the left and right subtrees (if negative, better not to include) let left_gain = max(Self::dfs(&n.left, max_sum), 0); let right_gain = max(Self::dfs(&n.right, max_sum), 0); // The maximum path sum with the current node as the highest point let current_path_sum = n.val + left_gain + right_gain; // Update the global maximum path sum *max_sum = max(*max_sum, current_path_sum); // Return the maximum contribution of the current node to its parent (can only choose one side) return n.val + max(left_gain, right_gain); } 0 }}fn main() { println!("Hello, world!");} |
c++
123456789101112131415161718192021222324252627282930313233 | class Solution {private: int maxSum = INT_MIN;public: int maxGain(TreeNode* node) { if (node == nullptr) { return 0; } // Recursively calculate the maximum contribution of the left and right child nodes // Only when the maximum contribution value is greater than 0, the corresponding child node is selected int leftGain = std::max(maxGain(node->left), 0); int rightGain = std::max(maxGain(node->right), 0); // The maximum path sum of a node depends on the node's value and the maximum contribution values of its left and right child nodes int priceNewpath = node->val + leftGain + rightGain; // Update the answer maxSum = std::max(maxSum, priceNewpath); // Return the maximum contribution value of the node return node->val + std::max(leftGain, rightGain); } int maxPathSum(TreeNode* root) { maxGain(root); return maxSum; }}; |
leetcode hot 100 rewrite
1234567891011121314151617181920212223242526 | class Solution { private: int sum; int __maxPathSum(TreeNode *root) { if (root == nullptr) return 0; int left_sum = __maxPathSum(root->left); int right_sum = __maxPathSum(root->right); sum = std::max({ left_sum + right_sum + root->val, root->val, root->val + left_sum, root->val + right_sum, sum }); return std::max(std::max(left_sum, right_sum) + root->val, root->val); } public: int maxPathSum(TreeNode *root) { sum = INT_MIN; __maxPathSum(root); return sum; }}; |
