LeetCode-Notes
  • Introduction
  • Records of Practice
  • 关于Github 不支持密码问题
  • 面试题
    • 搜索广告
    • 多模态大模型
    • 刷题记录
  • 算法代码实现
  • Python
    • Python 笔记
  • Spark
    • PySpark
    • Spark Issues
    • Spark调优笔记
  • FeatureEngineering
    • Feature Cleaning
    • Feature Selection
    • Feature Transformation
    • Feature Crossing
  • Recommendation Algorithm
    • Recall-and-PreRank
      • Non-Negative Matrix Fatorization(NMF)
      • Fatorization Machine(FM)
      • User-base/Item-base实现
      • 多路召回实现
    • Ranking
      • NeuralFM
      • DeepFM
      • Deep&Cross network (DCN)
    • DeepLearning-Basic
      • Attention
      • Dropout
      • Batch Norm
  • Machine Learning
    • XGBoost
    • Cross Entropy Loss
    • Other models
  • Graph Neural Network
    • GNN-1-Basic
  • Big Data
    • Reservoir Sampling
  • SQL
    • SQL and PySpark functions
    • Query Film Infomation
    • Create, Insert and Alter Actor Table
    • Manage Employment Data
    • Manage Employment Data -2
  • DataStructure
    • Searching
      • Find power
      • 2 Sum All Pair II
      • Two Sum
      • Search in Rotate Array
      • Search In Shifted Sorted Array II
      • Search in 2D array
      • Three Sum with duplicated values
      • Median of Two Sorted Arrays
    • Array
      • Longest Consecutive Subarray
      • Merge Two Array in-place
      • Trapping water
      • Rotate matrix
    • Sorting
      • Merge intervals
      • 排序
      • 最小的k个数
      • Find TopK largest- QuickSelect快速选择 method
      • MergeSort Linkedlist
      • 第K大元素
    • LinkedList
      • Reverse LinkedList I
      • Reverse K-group linked list
      • Detect Start of Cycle
      • HasCycle
      • DetectCycle II
      • 链表的共同节点
      • 链表中倒数第k个节点
      • 删除链表倒数第k个节点
      • 合并两个链表
      • 在排序数组中查找元素的第一个和最后一个位置
      • 删除链表里面重复的元素-1
    • Tree
      • Find Tree height (general iteration method)
      • Check BST and Check CompleteTree
      • ZigZag Order traversal
      • Binary Tree diameter I
      • Maximum Path Sum Binary Tree
      • Maximum Path Sum Binary Tree II
      • Binary Tree Path Sum To Target III
      • Tree diameter 树的直径II
      • Tree ReConstruction
      • Check if B is Subtree of A
      • The Kth smallest in Binary Search Tree
      • 打印Tree的右视图
      • 二叉搜索树的后序遍历序列
      • 重建二叉树
      • 判断二叉树是否对称
      • Path Sum to Target in Binary Tree
      • Tree-PreOrder-InOrder-PostOrder
    • Heap&Queue
      • Top-K smallest
      • 滑动窗口最大值
      • Find the K-Largest
    • 合并k个已排序的链表
    • String
      • Reverse String
      • 最长不含重复字符的子字符串
      • 最长回文串
      • 最长回文子序列-DP
    • DFS/BFS
      • Number of island
      • Number of Provinces
      • All Permutations of Subsets without duplication
      • All Permutations of Subsets with duplication
      • Combinations Of Coins
      • All Subset I (without fixing size of subset, without order, without duplication)
      • All Subset of K size without duplication II
      • All Subset of K size III (with duplication without considering order)
      • All Permutation II (with duplication and consider order)
      • Factor Combination-质数分解
    • DynamicProgramming
      • DP-解题过程
      • Find Continuous Sequence Sum to Target
      • 1800. Maximum Ascending Subarray Sum
      • NC91 最长上升子序列
      • 查找string的编码方式个数
      • Maximum Product
      • Longest Common Substring
      • Longest Common Substring-II
      • minEditCost
      • Backpack I
      • Array Hopper I
      • Minimum distance between strings
      • 最大正方形
  • Big Data Algorithms
    • Big Data Processing Algorithms
      • Reservior Sampling
      • Shuffle
      • MapReduce
      • Bloom Filter
      • BitMap
      • Heap For Big Data
Powered by GitBook
On this page

Was this helpful?

  1. DataStructure
  2. Tree

Maximum Path Sum Binary Tree II

Hard. 二叉树任意两个节点的最大路径和

PreviousMaximum Path Sum Binary TreeNextBinary Tree Path Sum To Target III

Last updated 4 years ago

Was this helpful?

1.Links:

牛客:

Laicode:

2. 题目:

Given a binary tree in which each node contains an integer number. Find the maximum possible sum from any node to any node (the start node and the end node can be the same).

Assumptions

  • ​The root of the given binary tree is not null

Examples

    -1
  /    \
2      11
     /    \
    6    -14

one example of paths could be -14 -> 11 -> -1 -> 2

another example could be the node 11 itself

The maximum path sum in the above binary tree is 6 + 11 + (-1) + 2 = 18

How is the binary tree represented?

We use the level order traversal sequence with a special symbol "#" denoting the null node.

For Example:

The sequence [1, 2, 3, #, #, 4] represents the following binary tree:

    1
  /   \
 2     3
      /
    4

3想法:

  1. 和之前的任意两个leaf node的最大路径不同的是,这个是任意两个node之间的最大路径,所以在把一个node的left, right subtree的max path相加之前,要先看一下来自left, right 的max path是否大于0。 如果是left/right 的从上往下的max path sum <0, 那么就不用加那个path了

  2. 思路:任意另个node的max path sum = max (left 的path sum, right的max path sum, left + right + node的跨了两个branchd的path sum) 对于每一个node,找到它left, right subtree的自上而下的consecutive max path sum,如果这个从上往下的path sum是等于0,就加到cur.value 否则如果是负数时,负数加上去不会对max path sum有贡献所以直接设置为0,不考虑。之后在和global max对比更新。最后把加上当前的node的value的从上往下的consecutive的max path sum返回到上一层。

  3. 步骤就是

    1. 遍历每一个node

    2. recursion的输入是node, 输出是从那个node开始自上往下最大的path sum

    3. 如果node是none,返回 0

    4. 在每一个node里面找到left, right children的自上往下的max path sum,如果自上往下max path sum >0, 就 left +right +node.val 得到从左往右的max path sum

    5. 把从左往右的max path sum和 global max path sum 对比并更新

    6. 返回加上当前节点的自上往下的max path sum

Source Code

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution(object):
  def maxPathSum(self, root):
    """
    input: TreeNode root
    return: int
    """
    # write your solution here
    # 1. question: input: root, output: maximum path sum from any node to any node
    # 2. idea:
    #   iterate every node in tree:
    #     for every node, find the max sum of its left consecutive path and max sum of its right consecutive path 
    #     compare the value of :  left path max sum, right path max sum, node.val and 
    #                            (left path max sum + right path max sum + node.val) and global max sum of path
    #    update global max sum of path of any two node, 更新任意两个node 之间的pathsum的最大值
    #    return max path sum of single path under this node 返回单条从上往下连续path的sum
    # Time: O(n), Space O(n) for imbalance tree, O(logn) for balance tree
    if not root:
      return None
    self.max_sum = -float('inf')
    self.helper(root)
    return self.max_sum
  def helper(self, node):
    if not node:
      return 0
    left = max(self.helper(node.left),0)
    right = max(self.helper(node.right),0)
    # if left or right <0, then no need to add them to max_path
    #  max_path can be single path or sum of two paths or only node.val
    # then compare it with the global max
    max_path = left + right + node.val
    self.max_sum = max(max_path, self.max_sum)
    # return the single path with max sum
    return max(left,right) +node.val

https://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a?tpId=196&tqId=37050&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-total%2Fquestion-ranking&tab=answerKey
https://app.laicode.io/app/problem/139