[LeetCode] Binary Tree Maximum Path Sum

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 ans;
    int maxx(TreeNode *root){
        if(root == NULL) return 0;
        int s1 = maxx(root -> left);
        int s2 = maxx(root -> right);
        int num = root -> val;
        if(s1 > 0) num += s1;
        if(s2 > 0) num += s2;
        if(ans < num) ans = num;
        return max(root -> val,max(s1,s2) + root -> val);
    }
    int maxPathSum(TreeNode *root) {
       ans = root -> val;
       maxx(root);
       return ans;
    }
};


發佈了152 篇原創文章 · 獲贊 0 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章