LeetCode - Binary Tree Maximum Path Sum 题解

来源:互联网 发布:淘宝网开店怎么开手机 编辑:程序博客网 时间:2024/06/06 02:17

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.

思路:

后续遍历,遇到负的就截掉。

class Solution {public:    int maxPathSum(TreeNode *root) {        maxx = -2147483648;        postOrder(root);        return maxx;    }private:    int maxx;    int postOrder(TreeNode *root){        if(!root)            return 0;        int l = postOrder(root->left);        int r = postOrder(root->right);        int v = max(l, r) + root->val;        maxx = max(maxx, l + r + root->val);        return max(v, 0);    }};




0 0
原创粉丝点击