Tencent 38-Max Path and Binary Tree

Tencent 38-Max path in binary tree and # leetcode124

Given a non-empty binary tree, return its maximum path sum.

In this problem, a path is defined as a sequence starting from any node in the tree and reaching any node . The path contains at least one node and does not necessarily pass through the root node.

Example 1:

Input: [1,2,3]

   1
  / \
 2   3

Output: 6
Example 2:

Input: [-10,9,20, null, null, 15,7]

-10
/
9 20
/
15 7

Output: 42

Hard level, not easy to understand,
refer to the Huahua sauce video, the
code is easy to write wrong
ans update, consider left and right,
the result of a node, you can only choose left or right

Analysis
For the tree shown below:

     a
   /   \
  b     c
 / \   / \ 
d   e f   g

The path of maximum sum is basically only in the following situations:

  • A node itself
  • It is a dbe-like "complete subtree" with a certain node b as the root node (the selected node must be joined by both left and right children or neither)
  • The form of dbacf contains "incomplete subtree" (such as the right child e of b is not added, and the right child g of c).
    Therefore, adopt the recursive idea, first traverse to the leaf node, and return the maximum path sum of the current branch layer by layer.

If the maximum path is 1 or 2, then there is no need to backtrack, that is, for 1 and 2, only the root + left + right path and the maximum path need to be determined, and there is no need to return the value to the upper layer; And 3 needs to continue to judge whether the current root + left or root + right is the left or right branch of the final path (such as db is the left branch of dbacf), so when you need to backtrack, you need to return the maximum of root + left and root + right If the left and right children of root are negative, then the current subpath is the root node itself, that is, return to root.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def _maxPathSum(self, root) :
        if root is None:return float('-inf')
        #经过左节点的路径的最大和
        l=max(0,self._maxPathSum(root.left))
        #经过右节点的路径的最大和
        r=max(0,self._maxPathSum(root.right))
        #以当前节点为根节点的路径最大和
        self.ans=max(self.ans,root.val+l+r)
        #返回 经过当前节点的路径最大和
        return max(l,r)+root.val
        
    def maxPathSum(self, root: TreeNode) -> int:
        #hard级别
        self.ans=float('-inf')
        self._maxPathSum(root)
        return self.ans
Published 93 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/zlb872551601/article/details/103650201