124. Binary Tree Maximum Path Sum
来源:互联网 发布:知其雄,守其雌哲学道理 编辑:程序博客网 时间:2024/06/04 20:53
问题描述
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 m; int maxPathSum(TreeNode* root) { if (!root) return 0; m = INT_MIN; int l_len = helper(root->left); int r_len = helper(root->right); int count = root->val; if (l_len > 0) count += l_len; if (r_len > 0) count += r_len; if (count > m) m = count; return m; } int helper(TreeNode* root) { if (!root) return 0; if (!root->left && !root->right) { if (root->val > m) m = root->val; return root->val; } int l_len = helper(root->left); int r_len = helper(root->right); int count = root->val; if (l_len > 0) count += l_len; if (r_len > 0) count += r_len; if (count > m) m = count; if (max(l_len,r_len) >0) return max(l_len,r_len)+root->val; else return root->val; }};
0 0
- Tree-----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
- 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
- 124. Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- [LeetCode] 124. Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum
- leetcode 124.Binary Tree Maximum Path Sum
- 如何得到比AlexNet更简单但是性能更好的网络?
- 洛谷 1288 取数游戏
- Ansible 系列之 Playbooks 剧本 (1)
- MongoDB使用小结:一些常用操作分享
- i=i++问题
- 124. Binary Tree Maximum Path Sum
- sockaddr和sockaddr_in的区别
- web开发学生信息管理系统
- #1474 : 拆字游戏
- 常用排序算法Java语言实现
- php扩展mongo数据库
- java通信之Scoket-UDP
- java的基础(一)
- 系统边界图