Binary Tree Maximum Path Sum

来源:互联网 发布:上海嘉定装修公司知乎 编辑:程序博客网 时间:2024/05/17 22:19

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.

解题思路:要求的是结果最大的那条路径,考虑递归遍历左右子数。

注意的地方为子树的返回值,返回的值为一条路径的最大值为max(根节点,max(根节点+左子树最大路径,根节点+右子树最大路径))

/** * 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 maxVal = INT_MIN;    int maxPathSum(TreeNode *root) {        if(root ==NULL){            return 0;        }        maxChildSum(root);        return maxVal;    }    int maxChildSum(TreeNode *root){        int value = root->val;        int lmax = 0;        int rmax = 0;        if(root->left){            lmax = maxChildSum(root->left);            if(lmax >=0)            {                value += lmax;            }        }        if(root->right){            rmax = maxChildSum(root->right);            if(rmax >=0)            {                value += rmax;            }        }        if(value > maxVal){            maxVal = value;        }        return max(root->val,max(root->val + lmax, root->val + rmax));    }    };




0 0
原创粉丝点击