124. Binary Tree Maximum Path Sum

来源:互联网 发布:yum安装 编辑:程序博客网 时间:2024/06/15 11:26

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.

题意是指,从任意结点出发,到达任意的结点算一条路径,然后求出这条路径的最大值。这一题挺难的,因为一开始无从下手,因为它并不一定是从根节点开始的,所以无论是递归还是非递归都不好下手。但是仔细想,不一定要从开始结点出发,可以通过深搜,从左、右结点出发,然后假如左右结点大于0的话,那么这个路径是往增加的方向发展的,所以可以加起来,然后合最大值进行比较;假如其中有结点小于0,那么这个路径可能就需要重新从0开始计算。一直到遍历整个二叉树。代码如下:

Code:(LeetCode运行19ms)

/** * 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 maxPathSum(TreeNode* root) {        max_sum = INT_MIN;        depthFirstSearch(root);        return max_sum;    }    private :    int max_sum;    int depthFirstSearch(TreeNode *root) {        if (!root) {            return 0;        }        int left = depthFirstSearch(root -> left);        int right = depthFirstSearch(root -> right);                int sum = root -> val;        if (left > 0) {            sum += left;        }        if (right > 0) {            sum += right;        }        max_sum = max(max_sum, sum);        return max(left, right) > 0 ? max(left, right) + root -> val : root -> val;    }};




原创粉丝点击