LeetCode //C - 124. Binary Tree Maximum Path Sum

这篇具有很好参考价值的文章主要介绍了LeetCode //C - 124. Binary Tree Maximum Path Sum。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

124. Binary Tree Maximum Path Sum

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node’s values in the path.

Given the root of a binary tree, return the maximum path sum of any non-empty path.
 

Example 1:

LeetCode //C - 124. Binary Tree Maximum Path Sum,LeetCode,leetcode,c语言,算法

Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

Example 2:

LeetCode //C - 124. Binary Tree Maximum Path Sum,LeetCode,leetcode,c语言,算法

Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

Constraints:
  • The number of nodes in the tree is in the range [ 1 , 3 ∗ 1 0 4 1, 3 * 10^4 1,3104]
  • -1000 <= Node.val <= 1000

From: LeetCode
Link: 124. Binary Tree Maximum Path Sum


Solution:

Ideas:

Overview:
The problem is to find the maximum path sum in a binary tree. A “path” here means 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.

Approach:
To solve this problem, we perform a post-order traversal of the tree. For each node, we calculate two things:

  1. The maximum path sum considering the current node as an endpoint.
  2. The maximum path sum that could be formed using the current node, which might include paths from its left and/or right child.

The reason we need both values is that while the first one (endpoint value) helps us build the path sum for the parent node, the second value (including the current node) helps us track the global maximum path sum across the tree.

Code Explanation:

  1. helper function: This is a recursive function that traverses the binary tree in a post-order manner. It calculates the maximum path sum for each node and updates the global maximum path sum.

  2. globalMax: This variable keeps track of the maximum path sum encountered so far across the entire tree.

  3. leftMax and rightMax: For each node, we calculate the maximum path sum for its left child and right child.

  4. maxSingle: This represents the maximum path sum considering the current node as an endpoint. This is calculated as the maximum of:

  • The node’s value itself.
  • The node’s value + maximum path sum of the left child.
  • The node’s value + maximum path sum of the right child.
  1. maxTop: This represents the maximum path sum that could be formed using the current node. This is calculated as the maximum of:
  • maxSingle (as explained above).
  • The path sum considering both left and right children + the current node’s value.
  1. globalMax update: For each node, we update the globalMax to be the maximum of the current globalMax and maxTop.

  2. Returning from helper function: We return maxSingle because this represents the maximum value that can be used to form a path sum for the current node’s parent.

  3. maxPathSum function: This function initializes the globalMax to the smallest possible integer value and then calls the helper function to traverse the tree and find the maximum path sum. Finally, it returns the globalMax.文章来源地址https://www.toymoban.com/news/detail-705820.html

Code:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int helper(struct TreeNode* root, int* globalMax) {
    if (!root) {
        return 0;
    }

    int leftMax = helper(root->left, globalMax);
    int rightMax = helper(root->right, globalMax);

    int maxSingle = fmax(fmax(leftMax, rightMax) + root->val, root->val);
    int maxTop = fmax(maxSingle, leftMax + rightMax + root->val);

    *globalMax = fmax(*globalMax, maxTop);

    return maxSingle;
}

int maxPathSum(struct TreeNode* root) {
    int globalMax = INT_MIN;
    helper(root, &globalMax);
    return globalMax;
}

到了这里,关于LeetCode //C - 124. Binary Tree Maximum Path Sum的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Leetcode 1022. Sum of Root To Leaf Binary Numbers (树遍历题)

    Sum of Root To Leaf Binary Numbers Easy 3.3K 183 Companies You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 - 1 - 1 - 0 - 1, then this could represent 01101 in binary, which is 13. For all leaves in the tree, cons

    2024年02月03日
    浏览(46)
  • LeetCode //C - 199. Binary Tree Right Side View

    Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.   Example 1: Input: root = [1,2,3,null,5,null,4] Output: [1,3,4] Example 2: Input: root = [1,null,3] Output: [1,3] Example 3: Input root = [] Output [] Constraints: The number of nodes in the tree is in t

    2024年01月20日
    浏览(35)
  • Leetcode 1367. Linked List in Binary Tree (二叉树好题)

    Linked List in Binary Tree Medium Given a binary tree root and a linked list with head as the first node. Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards. Exampl

    2024年01月25日
    浏览(47)
  • LeetCode //C - 114. Flatten Binary Tree to Linked List

    Given the root of a binary tree, flatten the tree into a “linked list”: The “linked list” should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The “linked list” should be in the same order as a pre-order traversal of the binary tree.   Example 1: Input: ro

    2024年02月09日
    浏览(36)
  • 小白水平理解面试经典题目LeetCode 404 Sum of Left Leaves【Tree】

    给定二叉树的root,返回所有左叶的总和。 叶子是没有子节点的节点。左叶是另一个节点的左子节点的叶。 在大学某个自习的下午,小白坐在教室看到这道题。想想自己曾经和白月光做题,现在大过年的,也是只有自己练题了。左边一颗树,右边一棵树。。。 这时候黑长直女

    2024年02月22日
    浏览(46)
  • Leetcode 3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K

    Leetcode 3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K 1. 解题思路 2. 代码实现 题目链接:3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K 这一题我的思路上就是一个二分的思路,先确定一个上下界,然后不断通过二分来找到最大的price不超过k的值。 因此,剩下的

    2024年01月20日
    浏览(43)
  • LeetCode //C - 106. Construct Binary Tree from Inorder and Postorder Traversal

    Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.   Example 1: Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] Output: [3,9,20,null,null,15,7] Example 2: Input: inorder = [-1], postorder = [-1] Outpu

    2024年02月09日
    浏览(33)
  • LeetCode //C - 105. Construct Binary Tree from Preorder and Inorder Traversal

    Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.   Example 1: Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] Output: [3,9,20,null,null,15,7] Example 2: Input: preorder = [-1], inorder = [-1] Output: [-

    2024年02月09日
    浏览(28)
  • leetcode第124场双周赛

    给你一个整数数组  nums  ,如果  nums   至少  包含  2  个元素,你可以执行以下操作: 选择  nums  中的前两个元素并将它们删除。 一次操作的  分数  是被删除元素的和。 在确保  所有操作分数相同  的前提下,请你求出  最多  能进行多少次操作。 请你返回按照上述

    2024年02月19日
    浏览(37)
  • leetcode做题笔记124. 二叉树中的最大路径和

    二叉树中的  路径  被定义为一条节点序列,序列中每对相邻节点之间都存在一条边。同一个节点在一条路径序列中  至多出现一次  。该路径  至少包含一个  节点,且不一定经过根节点。 路径和  是路径中各节点值的总和。 给你一个二叉树的根节点  root  ,返回其  最

    2024年02月10日
    浏览(47)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包