首页 > 其他分享 >124. Binary Tree Maximum Path Sum(难)

124. Binary Tree Maximum Path Sum(难)

时间:2022-12-01 20:10:16浏览次数:46  
标签:Binary right TreeNode int Sum Tree root maxSum left


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


​6​​.

 

编程之美: 求二叉树中节点的最大距离 很像

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode* root) {
if (root == NULL) return 0;
maxSum = INT_MIN;
maxPathDown(root);
return maxSum;
}

private:
int maxPathDown(TreeNode* root){
if (root == NULL) return 0;
int left = max(0,maxPathDown(root->left));
int right =max(0, maxPathDown(root->right));

maxSum = max(maxSum, left + right + root->val);

return max(left, right) + root->val;
}
int maxSum;
};



标签:Binary,right,TreeNode,int,Sum,Tree,root,maxSum,left
From: https://blog.51cto.com/u_15899184/5904039

相关文章

  • 98. Validate Binary Search Tree
    Givenabinarytree,determineifitisavalidbinarysearchtree(BST).AssumeaBSTisdefinedasfollows:Theleftsubtreeofanodecontainsonlynodeswit......
  • Remove Node in Binary Search Tree
    GivenarootofBinarySearchTreewithuniquevalueforeachnode.Removethenodewithgivenvalue.Ifthereisnosuchanodewithgivenvalueinthebinary......
  • lintcode:Binary Tree Serialization
    Designanalgorithmandwritecodetoserializeanddeserializeabinarytree.Writingthetreetoafileiscalled‘serialization’andreadingbackfromthe......
  • lintcode:Subarray Sum Closest
    Givenanintegerarray,findasubarraywithsumclosesttozero.Returntheindexesofthefirstnumberandlastnumber.ExampleGiven[-3,1,1,-3,5],retur......
  • Lorem Ipsum
    Loremipsumdolorsitamet,consecteturadipiscingelit.Nullamegetnuncneclectusvenenatiseuismodatsedmetus.Pellentesqueeuorcisitametsemluctusd......
  • 【题解】ABC237G Row Column Sums 2(感谢强大 alpha!!1【3】)
    题意:求\(n\timesn\)方阵个数,满足每列之和为\(R_i\),每行之和为\(C_i\)。数据范围:\(0\leqR_i,C_i\leq2\),\(n\leq10^7\)。转二分图,相当于限定左侧每个点和右侧......
  • 1. Two Sum
    1.TwoSumGivenanarrayofintegersnums andanintegertarget,returnindicesofthetwonumberssuchthattheyadduptotarget.Youmayassumethateach......
  • SQL-runoob-function-sum
    mysql>SELECT*FROMaccess_log;+-----+---------+-------+------------+|aid|site_id|count|date|+-----+---------+-------+------------+|1|......
  • stream流进行tree树组装
    1.准备工具类。packagecom.joolun.mall.util;importcom.joolun.mall.entity.TreeNode;importlombok.experimental.UtilityClass;importjava.util.ArrayList;im......
  • POJ - 1308 Is It A Tree?(并查集)
    POJ-1308IsItATree?(并查集)题目大意:传送门对于每一组测试样例,给出若干条无向边,判断由这些无向边构成的图是否为无环连通图题目分析:要点1:无环联通图(树)的性质:边......