Binary Tree Maximum Path Sum

来源:互联网 发布:研究院与研究生院 知乎 编辑:程序博客网 时间:2024/04/29 11:02

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1      / \     2   3

Return 6.

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int maxPathSum(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int max = 0;        int result = maxSum(root, max);        return max > result ? max : result;    }    private:    int maxSum(TreeNode *root, int& max_path) {                if (root->left == NULL && root->right == NULL) {            max_path = root->val;            return root->val;        } else if (root->right == NULL) {            int lmax = 0;            int ls = maxSum(root->left, lmax);            int sum = root->val + ls;            max_path = ls > lmax ? ls : lmax;            max_path = max_path > sum ? max_path : sum;            return sum > root->val ? sum : root->val;        } else if (root->left == NULL) {            int rmax = 0;            int rs = maxSum(root->right, rmax);            int sum = root->val + rs;            max_path = rs > rmax ? rs : rmax;            max_path = max_path > sum ? max_path : sum;            return sum > root->val ? sum : root->val;        } else {            int lmax = 0, rmax = 0;            int ls = maxSum(root->left, lmax);            int rs = maxSum(root->right, rmax);            int sumr = root->val + rs;            int suml = root->val + ls;            int sum = root->val + rs + ls;            max_path = lmax > rmax ? lmax : rmax;            max_path = max_path > rs ? max_path : rs;            max_path = max_path > ls ? max_path : ls;            max_path = max_path > suml ? max_path : suml;            max_path = max_path > sumr ? max_path : sumr;            max_path = max_path > sum ? max_path : sum;            int max = suml > sumr ? suml : sumr;            return max > root->val ? max : root->val;        }    }};


原创粉丝点击