#94 Binary Tree Maximum Path Sum
来源:互联网 发布:java hdfs框架 编辑:程序博客网 时间:2024/05/18 03:48
题目描述:
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
Example
题目思路:Given the below binary tree:
1 / \2 3
return 6
.
这题因为path可以起始/终止于任何一个node,似乎不太好下手。但是可以发现,无论怎样,path都会经过某些node。那如果对于某一node,它的左子树(包含左节点)出一条path(这条path必须不能同时包含左子树的左右子树),右子树(包含右节点)出一条path,那么max可能是左path,或者右path,或者只是这个node本身,或者是左path+node+右path。
Mycode(AC = 51ms):
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /** * @param root: The root of binary tree. * @return: An integer */ int maxPathSum(TreeNode *root) { // write your code here if (root == NULL) { return 0; } int max_sum = INT_MIN; maxPathSum(root, max_sum); return max_sum; } int maxPathSum(TreeNode *root, int& max_sum) { if (!root->left && !root->right) { max_sum = max(max_sum, root->val); return root->val; } int left = INT_MIN, right = INT_MIN, result = INT_MIN; // get the max path from left subtree (include left node) if (root->left) { left = maxPathSum(root->left, max_sum); result = max(root->val, root->val + left); } // get the max path from right subtree (include right node) if (root->right) { right = maxPathSum(root->right, max_sum); result = max(result, max(root->val, root->val + right)); } if (left != INT_MIN && right != INT_MIN) { max_sum = max(left + right + root->val, max(max_sum, result)); } else { max_sum = max(max_sum, result); } return result; }};
0 0
- #94 Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- 收集整理
- java中几种Map在什么情况下使用,并简单介绍原因及原理
- idea 搭建ssm遇到的问题
- 第一行代码 第八章源码漏洞
- 自定义二维码以及扫描二维码
- #94 Binary Tree Maximum Path Sum
- iptables mangle 表,链
- 一份不负责任的Keras介绍
- ubuntu设置java环境
- Mybatis返回结果时发生的类型转换异常
- [LeetCode]Intersection of Two Arrays II(Java)
- python 调用 nmap 扫描服务器开放的端口
- Running in a Background Service 之Reporting Work Status
- 一些证明