Leetcode 124. Binary Tree Maximum Path Sum

Given a non-empty 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.

在这里插入图片描述
此题的path定义具有迷惑性,所以一开始可能写错,只能得到部分用例,具体解释可参见
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/39811/What-is-the-meaning-of-path-in-this-problem

method 1

要得到树中从一个结点到另一个结点的最大路径和,根据总结的一般规律,可归结为对树的后序遍历。因为对一颗树,要先得到其左子树和右子树的路径和,才能决定到底是取哪一边,因此后序遍历符合要求。
边遍历,边求最大值,最后完成本棵树的路径求和时,要将最大路径和返回给父结点,最大路径和有三种情况:左子树路径+根节点,右子树路径+根节点,根节点

    int postOrder(TreeNode* root, int& maxSum){
	    if (!root) return 0;

    	int left = postOrder(root->left, maxSum);
	    int right = postOrder(root->right, maxSum);
	    int val = root->val;

    	int curSum = max(val, max(left + val, max(right + val, left + right + val)));
	    maxSum = max(curSum, maxSum);

    	return max(val, max(left+val, right + val));
}

    int maxPathSum(TreeNode* root) {
        if(!root) return 0;
	    int maxSum = root->val;
	    postOrder(root, maxSum);
	    return maxSum;
}

summary

  1. 树的问题归纳为遍历顺序的问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值