LeetCode—***寻找二叉树中任意两个节点之间的最大值Binary Tree Maximum Path Sum
来源:互联网 发布:安卓windows桌面主题 编辑:程序博客网 时间:2024/06/14 17:08
Binary Tree Maximum Path Sum
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
.
这里用一个全局变量,记录left+root+right的最大值
之前对递归算法很不熟悉,其实只要将一层递归逻辑理清楚,然后有退出的条件,就可以了
/** * 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 max = -9999; int FindMax(TreeNode * root) { int value = root->val; int leftValue = 0; int rightValue = 0; int rt; if(root == NULL) { return 0; } if(root->left != NULL) { leftValue = FindMax(root->left); if(leftValue > 0) value += leftValue; } if(root->right != NULL) { rightValue = FindMax(root->right); if(rightValue > 0) value += rightValue; } if(value > max) { max = value; //<用max记录root+left+right的最大值 } if(root->val > (root->val+leftValue)) { rt = root->val; } else { rt = root->val+leftValue; } if(rt < (root->val+rightValue)) //<返回root,root+left.root+right中的最大值 { rt = root->val+rightValue; } return rt; } int maxPathSum(TreeNode *root) { if(NULL == root) { return 0; } FindMax(root); return max; }};
0 0
- LeetCode—***寻找二叉树中任意两个节点之间的最大值Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum (二叉树路径和的最大值) 【leetcode】
- LeetCode | Binary Tree Maximum Path Sum(二叉树的路径最大值)
- Binary Tree Maximum Path Sum 二叉树中任意路径的最大和
- LeetCode(Binary Tree Maximum Path Sum) 在二叉树中找出一条和最大的路径
- [LeetCode 124] Binary Tree Maximum Path Sum (DFS/二叉树)
- 二叉树-Binary tree maximum path sum
- leetcode---binary-tree-maximum-path-sum---树
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- Binary Tree Maximum Path Sum 二叉树最大路径和 @LeetCode
- Leetcode 124 Binary Tree Maximum Path Sum 二叉树最大路径和
- LeetCode 124. Binary Tree Maximum Path Sum(二叉树最大路径和)
- 【LeetCode】Binary Tree Maximum Path Sum二叉树中的最大路径和
- leetcode解题之124. Binary Tree Maximum Path Sum Java版 (二叉树的最大路径和)
- Binary Tree Maximum Path Sum 二叉树最大路径和
- 【DFS&二叉树】Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- Qt Model/View 学习笔记 (三)
- C++学习笔记
- 【读书笔记】【收获,不止Oracle】不同连接类型表下,驱动顺序对查询性能的影响
- Android之ContextMenu的使用方法以及与OptionMenu的区别
- 金庸武侠小说之我的见解
- LeetCode—***寻找二叉树中任意两个节点之间的最大值Binary Tree Maximum Path Sum
- poj2373 灌溉草场
- linux上编译mongodb c++ 客户端sdk
- Qt Model/View 学习笔记 (四)
- UVa10803_Thunder Mountain(最短路)(小白书图论专题)
- 单向链表的操作
- 实例学习gcc+gdb+make
- HDOJ 1171 Big Event in HDU(多重背包)
- HDU 1203 I NEED A OFFER!(01背包)