Leetcode -- Binary Tree maximum path sum

Source: Internet
Author: User

Recursion, DFS

The returned value is a pair <int, int>. First indicates the maximum pathsum of the two subtree that does not pass through the current root; second indicates the two subtree, use root-> left and root-> right as the maximum value of the path of the Start Node of the path.

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     int maxPathSum(TreeNode *root) {13         pair<int,int> res = dfs(root);14         return res.first;15     }16     pair<int,int> dfs(TreeNode *root)17     {18         if(root == NULL)19         {20             return make_pair(0,0);21         }22         pair<int,int> left = dfs(root->left);23         pair<int,int> right = dfs(root->right);24         int leftCrossMax = left.first;25         int rightCrossMax = right.first;26         27         int leftMax = left.second > 0?left.second:0;28         int rightMax = right.second > 0?right.second:0;29         30         int maxNoCross = INT_MIN;31         if(root->left != NULL)32         {33             maxNoCross = max(maxNoCross,leftCrossMax);34         }35         if(root->right != NULL)36         {37             maxNoCross = max(maxNoCross,rightCrossMax);38         }39         int maxCross = leftMax+rightMax+root->val;40         int maxSum = max(maxCross,maxNoCross);41         42         int child = max(leftMax,rightMax);43         int maxChild = child > 0?child+root->val:root->val;44         return make_pair(maxSum,maxChild);45     }46 };

 

Leetcode -- Binary Tree maximum path sum

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.