112_leetcode_Binary Tree Maximum Path

来源:互联网 发布:主宰西游装备进阶数据 编辑:程序博客网 时间:2024/06/09 17:33

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.

1:递归;2:后序遍历;3:节点的值是负数



       int maxPathSum(TreeNode *root)    {        if(root == NULL)        {            return 0;        }        if(!root->left && !root->right)        {            return root->val;        }                int value = INT_MIN;                maxPathSumCore(root, value);                return value;    }        int maxPathSumCore(TreeNode *root, int &value)    {        if(root == NULL)        {            return 0;        }                int leftLength = maxPathSumCore(root->left, value);        int rightLength = maxPathSumCore(root->right, value);                int curLength = max(root->val, root->val + max(leftLength, rightLength));                int tempValue = max(curLength, leftLength + rightLength + root->val);                if(tempValue > value)        {            value = tempValue;        }                return curLength;    }


0 0
原创粉丝点击