leetcode 124. Binary Tree Maximum Path Sum
来源:互联网 发布:java类的调用 编辑:程序博客网 时间:2024/06/06 03:12
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 must contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 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) { maxPath = INT_MIN; helper(root); return maxPath; }private: int maxPath; int helper(TreeNode* root) //返回 包括自己在内的最大值 给上一层节点 { if (!root->left && !root->right) //左右节点都没有 { maxPath = max(maxPath, root->val); return root->val; } else if (!root->left && root->right) { int rc = helper(root->right); rc = rc > 0 ? rc : 0; maxPath = max(maxPath, root->val + rc); return root->val + rc; } else if (root->left && !root->right) { int rl = helper(root->left); rl = rl > 0 ? rl : 0; maxPath = max(maxPath, root->val + rl); return root->val + rl; } else { int rc = helper(root->right); int lc = helper(root->left); rc = rc > 0 ? rc : 0; lc = lc > 0 ? lc : 0; maxPath = max(maxPath, root->val + rc + lc); //弯曲的情况,当前节点是弯曲点 return root->val + max(rc, lc); } } };
阅读全文
0 0
- LeetCode 124. Binary Tree Maximum Path Sum
- [LeetCode]*124.Binary Tree Maximum Path Sum
- [Leetcode] 124. Binary Tree Maximum Path Sum
- [leetcode] 124. Binary Tree Maximum Path Sum
- [leetcode] 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- [LeetCode] 124. Binary Tree Maximum Path Sum
- leetcode 124.Binary Tree Maximum Path Sum
- leetcode-124. Binary Tree Maximum Path Sum
- [LeetCode]124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- LEETCODE 124. Binary Tree Maximum Path Sum
- 芯片制造全工艺流程详情,请收藏!
- [IOS笔记]UITableView及索引条
- Linux 一台服务器部署多个tomcat
- 在sublime text 3中编译javascript
- Refs and the DOM
- leetcode 124. Binary Tree Maximum Path Sum
- Input.GetAxis()
- 基于UVM的verilog验证
- ccf 炉石传说
- 201703-1分蛋糕
- should be described in NUMA config 和 CPU feature cmt not found
- mysql增加,删除,查看唯一索引
- 【bzoj4720】【noip2016】【换座位】期望dp+Floyd
- uiautomator自动化脚本