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

Laicode: https://app.laicode.io/app/problem/138 二叉树任意两个leaf node的最大路径和

PreviousBinary Tree diameter INextMaximum Path Sum Binary Tree II

Last updated 4 years ago

Was this helpful?

Link

Laicode:

Given a binary tree in which each node contains an integer number. Find the maximum possible sum from one leaf node to another leaf node. If there is no such path available, return Integer.MIN_VALUE(Java)/INT_MIN (C++).

Examples

-15

/ \

2 11

/ \

6 14

The maximum path sum is 6 + 11 + 14 = 31.

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

想法: top-down (更新global max) + bottom up(返回从上往下的path的最大的sum)

  1. 把每个node遍历一遍

  2. 在每个node里面,找到left 的path sum和right path sum(如果存在), 并把left path, right path node.val相加得到最远的两个leaf node的path的sum

  3. 对比这个path sum和global max,更新global max

  4. 返回加上当前的node.val的一条在root node到leaf node的path上面的最大的path,即max(left,right)+node.val,就返回当前最大的single path

Source Code

class Solution(object):
  def __init__(self):
    self.res = 0
  def maxPathSum(self, root):
    """
    input: TreeNode root
    return: int
    """
    # write your solution here
    #1.  question: input: tree node root, output : max path sum from
    #  one leaf node to another leaf node. The max diameter of tree
    # 1. idea : Top-down 
    # 把每个node遍历一遍, 在每个node 里面,找左边和右边最大的 path sum, 再 加上现在的node的value
    # 把更新的path 和之前的对比和更新
    # start from the top and go down, for each node, consider it as the root node of the path
    #  we need to find the max path sum from right, left branch and then add them with the cur
    #  node value
    #  then compare this value with global max
    #   recursion: 
    #      input: node ,  max_path sum
    #      output: max path sum found in current node, cur node height
    #  base case:
    #
    # base: if root none:  MIN
    # Time: O(n) , n = tree node number  Space O(logn) logn = tree height if tree is balance
    #
    
    self.ans = -2147483648
    self._maxPathSum(root)
    return self.ans

  def _maxPathSum(self, root):
        if not root: return -2147483648
        l =  self._maxPathSum(root.left)
        r = self._maxPathSum(root.right)
        if l != -2147483648 and r !=-2147483648:
          self.ans = max(self.ans, root.val + l + r)
          return root.val + max(l, r)
        elif l!= -2147483648 :
          return root.val + l
        elif r!= -2147483648 :
          return root.val + r
        return root.val 

https://app.laicode.io/app/problem/138
https://app.laicode.io/app/problem/140