leetcode_c++:树:Binary Tree Maximum Path Sum(124)

来源:互联网 发布:matlab 画数组 编辑:程序博客网 时间:2024/06/08 10:30

Given a 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 does not need to go through the root.

For example:
Given the below binary tree,

       1      / \     2   3

return 6


算法

求一棵二叉树上的最大路径。

直接 DFS 就可以了,返回以这一棵子树且一端在上的最大路径,然后维护一个最大路径就行了。


class Solution {private:    int ret;    int dfs(TreeNode *root) {        if (root == NULL)            return 0;        int left_sum = max(0, dfs(root->left));        int right_sum = max(0, dfs(root->right));        ret = max(ret, left_sum + right_sum + root->val);        return max(left_sum, right_sum) + root->val;    }public:    int maxPathSum(TreeNode *root) {        ret = INT_MIN;        dfs(root);        return ret;    }};
0 0
原创粉丝点击