Binary Tree Maximum Path Sum

来源:互联网 发布:淘宝app收藏店铺 编辑:程序博客网 时间:2024/05/16 01:28

LeetCode :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.

题意:给出一个二叉树,求最大路径和。路径的起点和终点可以是树中任意节点。

解题思路:对于树中的任意节点来说,包括该节点在内的路径和可以表示为:node.val + F(node->left) + F(node->right),即:节点值+左子树的路径和+右子树的路径和(其中F(node->left)表示node左子树路径和),这是一个递归的定义。找出最大和就是需要的结果。

class Solution {int maxPathSum_dfs(TreeNode* root, int *maxSum){if (NULL == root){return 0;}//求出节点root的左子树的路径和、右子树的路径和int l = maxPathSum_dfs(root->left, maxSum);int r = maxPathSum_dfs(root->right, maxSum);//如果子树路径和小于零则归零,因为如果子树路径和小于零,则不会累加到路径和当中if (l < 0) l = 0;if (r < 0) r = 0;//判断root->val + F(root->left) + F(root->right)是否大于当前保存的最大值if (l + r + root->val > *maxSum)*maxSum = l + r + root->val;//返回路径和(由于返回的是路径,因此只能从左子树和右子树当中选一个较大的路径和返回)return root->val + (l>r ? l : r);}public:int maxPathSum(TreeNode *root) {int maxSum = INT_MIN;maxPathSum_dfs(root, &maxSum);return maxSum;}};





0 0
原创粉丝点击