LeetCode: Binary Tree Maximum Path Sum
来源:互联网 发布:数据库系统概论笔记 编辑:程序博客网 时间:2024/06/06 00:13
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 maxPathSum(TreeNode *root) { max = INT_MIN; buildMaxMap(root); return max; } int buildMaxMap(TreeNode* node) { if(node == NULL) return 0; int maxL = buildMaxMap(node->left); int maxR = buildMaxMap(node->right); int maxNode = std::max(std::max(maxL, maxR) + node->val, node->val); int curMax = std::max(std::max(maxL + maxR + node->val, node->val), maxNode); if(curMax > max) max = curMax; return maxNode; }private:int max; };
Round 2:
/** * 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 maxPathSum(TreeNode *root) { result = INT_MIN; helper(root); return result; }private: int helper(TreeNode *root) { if(root == NULL) return 0; int left = helper(root->left); int right = helper(root->right); int curMax = 0, localMax = 0; curMax = std::max(std::max(left, right) + root->val, root->val); localMax = std::max(curMax, left + right + root->val); if(localMax > result) result = localMax; return curMax; } int result; };
0 0
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- [Leetcode]Binary Tree Maximum Path Sum
- Leetcode: Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum
- 【Leetcode】Binary Tree Maximum Path Sum
- LeetCode | Binary Tree Maximum Path Sum
- ARP:地址解析协议实现学习
- CF_#268_DIV2_A_B_D
- HDU 1005 Number Sequence (循环节)
- Oracle RMAN备份单个文件的并发执行
- HDU 5025 Saving Tang Monk(bfs)
- LeetCode: Binary Tree Maximum Path Sum
- 机器人走迷宫问题
- 快播5.0官方免费版 精简版
- mysql 参数配置
- mysql索引类型
- <input autocomplete="off" />属性
- Ruby全局变量
- C++实现"类java"代码
- tomcat6和tomcat7的user配置