【面试题 & LeetCode 124】Binary Tree Maximum Path Sum

题目描述

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

思路

dfs求包括当前根节点值的最大路径和。

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    int maxPathSum(TreeNode* root) {
        if (root == NULL) return 0;
        int ans = root->val;
        dfs(root, ans);
        return ans;
    }
    
    int dfs(TreeNode* root, int& ans) {
        if (root == NULL) {
            return INT_MIN;
        }
        int left = dfs(root->left, ans);
        int right = dfs(root->right, ans);
        ans = max(ans, root->val + max(0, left) + max(0, right));
        return max(max(0, left), max(0, right)) + root->val;
    }
};
发布了340 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/105672254