LeetCode OJ - Binary Tree Maximum Path Sum

来源:互联网 发布:用c语言计算圆的面积 编辑:程序博客网 时间:2024/06/07 13:51

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.


分析:第一次错误分析,以为都是正数只要找出最大深度max1, 和次大深度max2,ret = max1 + max2 - root->val就可以了。没想到有负数情况。看来考虑问题要多琢磨
分析一:val值都为正数,那么会是个简单题。
class Solution {public:    int depth1 = 1;  //最大的深度    int depth2 = 1;  //次大的深度    int maxPathSum(TreeNode *root) {        if(!root) return 0;                depth1 = root->val;        depth2 = root->val;        DFS(root, 0);        return depth1 + depth2 - root->val;    }        void DFS(TreeNode *root, int path) {        path += root->val;        if(!root->left && !root->right) {            //替换最大            if(path > depth2 && path > depth1) {                depth2 = depth1;                depth1 = path;            }            //替换次大            if(path > depth2 && path < depth1) {                depth2 = path;            }            return ;        }        if(root->left) DFS(root->left, path);        if(root->right) DFS(root->right, path);    }};

分析二:这道题明显可以用递归思想来考虑,设跟节点的值为 max, 左子树的最大路径值为 lmax,右子树的最大路径值为 rmax。故最后的结果在下面几种情况中
lmax
lmax + max
lmax + max + rmax
max
max + rmax
rmax
看来对于没有直接规律而言的题目,采用分治法的策略还是不错的。一步无法计算出所有结果,采用分步解决可能合适。分治法是高屋建瓴的顶层设计模式,对于解决复杂问题很有效。(实际练习中的体会,非教材中感悟)





0 0