算法与数据结构 / 35

递归复习:深度与路径和

数据结构、边界条件与实现过程。 递归复习:深度与路径和。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

  • Bottom-up

    1. What do you expect from your left child/right child?
    2. What do you want to do in the current layer?
    3. What do you want to return to your parents?
  • Top-down

    1. 以参数传递信息,用一个class的attributes来记录最终结果
    2. 通常不需要返回值(但任然遵循递归调用顺序)
    3. 思维上更straight-forward,但代码不如bottom-up简洁
    4. 大部分需要输出完整path的题,top down更实用
      如果依赖subtree的结果,bottom up

1. Given a binary tree, find its minimum depth

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

最小深度: 根到最近叶的节点数;单边链不能把不存在的子树当作长度0的候选路径。Bottom-up用∞排除空分支,Top-down只在真实叶更新最短深度。

  • Bottom up
PYTHON · 仅供阅读
class Solution_bottom_up(object):
    def minDepth(self, root):
        if not root:
            return 0
        return self.helper(root)

    def helper(self, root):
        if not root:
            return float('inf')  # 不是返回0
        if root.left is None and root.right is None:
            return 1

        l = self.helper(root.left)
        r = self.helper(root.right)
        return min(l, r) + 1
  • Top down
PYTHON · 仅供阅读
class Solution_top_down(object):
    def minDepth(self, root):
        if not root:
            return 0
        
        self.ret = float('inf')
        self.helper(root, 0)
        return self.ret

    def helper(self, root, depth):
        if not root:
            return

        if root.left is None and root.right is None:
            self.ret = min(self.ret, depth + 1)
            return

        self.helper(root.left, depth + 1)
        self.helper(root.right, depth + 1)

        return
  • Top down 2
PYTHON · 仅供阅读
self.helper(root, 0) -> self.helper(root, 1)
PYTHON · 仅供阅读
class Solution2(object):
    def minDepth(self, root):
        if not root:
            return 0
        self.ret = float('inf')
        self.helper(root, 1)  #
        return self.ret

    def helper(self, root, depth):
        if not root:
            return

        if root.left is None and root.right is None:
            self.ret = min(self.ret, depth)  #
            return

        self.helper(root.left, depth + 1)
        self.helper(root.right, depth + 1)

        return

2. Max path sum from leaf to root

根到叶最大和: 当前节点返回自身值加左右真实根到叶路径中的较大者;空分支用−∞避免负权树错误地提前结束。

  • Bottom up
PYTHON · 仅供阅读
class Solution(object):
    def maxPathSumLeafToRoot(self, root):
        if root is None:
            return -float('inf')
        
        if root.left is None and root.right is None:
            return root.val
        
        left = self.maxPathSumLeafToRoot(root.left)
        right = self.maxPathSumLeafToRoot(root.right)
        return max(left, right) + root.val
  • Top down

Top-down状态: 参数curSum表示当前节点之前的路径和,在叶节点用curSum+node.val更新答案;到孩子时继续加当前节点值。

PYTHON · 仅供阅读
class Solution1(object):
    def maxPathSumLeafToRoot(self, root):
        if root is None:
            return -float('inf')
        
        self.retValue = -float('inf')
        self.helper(root, 0)
        return self.retValue

    def helper(self, node, curSum):
        if not node:
            return
        
        if node.left is None and node.right is None:
            self.retValue = max(self.retValue, curSum + node.val)
            return
        
        self.helper(node.left, curSum + node.val)
        self.helper(node.right, curSum + node.val)
        return
  • Top down 2
PYTHON · 仅供阅读
self.helper(root, 0) -> self.helper(root, root.val)

另一计数约定: 如果初始参数已含root.val,进入孩子时应加child.val,叶节点直接取curSum。两种约定都可行,但不能重复加节点。

PYTHON · 仅供阅读
class Solution2(object):
    def maxPathSumLeafToRoot(self, root):
        if root is None:
            return -float('inf')
        
        self.retValue = -float('inf')
        self.helper(root, root.val)  #
        return self.retValue

    def helper(self, node, curSum):
        if not node:
            return
        
        if node.left is None and node.right is None:
            self.retValue = max(self.retValue, curSum)  #
            return
        
        if node.left:
            self.helper(node.left, curSum + node.left.val)  #
            
        if node.right:
            self.helper(node.right, curSum + node.right.val)  #
        return

3. Binary tree path sum to target I

Given a binary tree and a target sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given target.

路径和例子: 目标16,若有根到叶路径5→8→3,则5+8+3=16可返回True;只在内部节点达到16而其后仍有孩子,不算根到叶完成路径。

  • Top down (recommended)
PYTHON · 仅供阅读
class Solution(object):
    def exist(self, root, target):
        self.target = target
        self.ret = False
        self.helper(root, 0)
        return self.ret

    def helper(self, root, current):
        if root is None:
            return False

        if root.left is None and root.right is None:
            self.ret = (self.ret or (current + root.val == self.target))
            return

        # 剪枝
        if self.ret == True:
            return

        self.helper(root.left, current + root.val)
        self.helper(root.right, current + root.val)
        return
  • Bottom up
    1. What do you expect from your left child/right child?
      • True: any root-to-leaf path include child has target sum
      • False: None
    2. What do you want to do in the current layer?
      • do nothing, pass current sum down
    3. What do you want to return to your parents?
      • True: any root-to-leaf path include you has target sum
      • False: None
PYTHON · 仅供阅读
class Solution1(object):
    def exist(self, root, target):
        self.target = target
        return self.helper(root, 0)

    def helper(self, root, current):
        if root is None:
            return False

        if root.left is None and root.right is None:
            return current + root.val == self.target

        return self.helper(root.left, current + root.val) or \
               self.helper(root.right, current + root.val)
  • My solution
PYTHON · 仅供阅读
class Solution2(object):
    def exist(self, root, target):
        if not root:
            return False

        if root.left is None and root.right is None:
            return root.val == target

        return self.exist(root.left, target - root.val) or \
               self.exist(root.right, target - root.val)

4. Maximum questions

4.1 Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

最大子数组递推: ending=max(num,ending+num),best=max(best,ending)。例如[4,-1,-2,1,5]整段和7;若全负,应返回最大单个负数而不是0。所有候选连续子数组都有一个结束位置,所以扫描每个结束位置即可。

TC=O(n)TC=O(n)
SC=O(1)SC=O(1)

PYTHON · 仅供阅读
def maxSubArray(array):
    prev = 0
    global_max = array[0]
    for num in array:
        prev = max(prev + num, num)
        global_max = max(global_max, prev)
    return global_max

4.2 Max path sum binary tree III

Max sum from 祖先到后代的一条向下路径(本节两种实现不允许在节点处转向).

向下路径例子: 11→14的和25可以作为候选;这里路径只沿祖先到后代延伸,不能同时合并左右分支。真正任意两点路径见4.4。

  • Top down (recommeded)

Top-down更新: 当前向下最优为max(node.val,prev+node.val),再更新全局答案;若prev为负,重新从当前节点开始。

PYTHON · 仅供阅读
class Solution(object):
    def maxPath(self, root):
        self.result = root.val
        self.helper(root, 0)
        return self.result

    def helper(self, root, prev):
        if root is None:
            return
        
        prev = max(root.val, prev + root.val)         
        self.result = max(self.result, prev)
        self.helper(root.left, prev)
        self.helper(root.right, prev)
  • bottom up (not recommeded)

Bottom-up的四个局部情形: 左正右负取左;右正左负取右;两边正只能选较大一边向父返回;两边负均舍弃而只取当前值。即down=node.val+max(0,left_down,right_down),此节仍不允许在节点处连接两支。

  1. What do you expect from your left child/right child?
    • Left: the largest sum path that starts at lchild
    • Right: the largest sum path that starts at rchild
  2. What do you want to do in the current layer?
    • update global_max with max(leftSum, rightSum, 0) + root.val
  3. What do you want to return to your parents?
    • Max(leftSum, rightSum, 0) + root.val

Case 1: left sum bigger

Case 2: right sum bigger

Case 3: both < 0

PYTHON · 仅供阅读
class Solution(object):
    def maximunPathSumBinaryTree(self, root):
        self.result = -float('inf')
        self.helper(root)
        return self.result
    
    def helper(self, root):
        if root is None:
            return 0
        
        left_largest_sum = self.helper(root.left)
        right_largest_sum = self.helper(root.right)
        
        max_ending_here = max(0, left_largest_sum, right_largest_sum) + root.val
        self.result = max(self.result, max_ending_here)
        
        return max_ending_here

4.3 Max path sum binary tree I

Find the max possible sum from one leaf node to another.

叶到叶: 当前左右孩子都存在时,可用left_leaf_sum+node.val+right_leaf_sum更新全局;向父返回只能选其中一边。只有一个孩子时必须沿真实孩子继续,不能用0伪装不存在的叶。

  1. What do you want from your lchild, rchild?
    • left: max “root to leaf” path sum of left subtree
    • right: max “root to leaf” path sum of right subtree
  2. What should you do on current layer?
    • calculate left + right + root.val
    • update globalMax if possible (only for full node: 左右必须都有child)
  3. What do you report to your parent?
    • max path sum from root to leaf
      i.e return max(left + right) + root.val
PYTHON · 仅供阅读
class Solution(object):
    def maxPathSum(self, root):
        self.result = -float('inf')
        self.helper(root)
        return self.result

    def helper(self, root):
        if not root:
            return 0
        if root.left is None and root.right is None:
            return root.val

        left = self.helper(root.left)
        right = self.helper(root.right)
        if root.left and root.right:  # 当且仅当full node的时候才更新
            self.result = max(self.result, left + right + root.val)
            return max(left, right) + root.val
        else:  # 否则,左右谁有值返回谁
            return root.val + right if root.left is None else root.val + left

整理注: 不足两个叶节点时,严格的叶到叶路径不存在;本实现返回负无穷作为无解哨兵。

4.4 Max path sum binary tree II

Find the max possible sum from any node to any node.

PYTHON · 仅供阅读
class Solution(object):
    def maxPathSum(self, root):
        self.result = -float('inf')
        self.helper(root)
        return self.result

    def helper(self, root):
        if root is None:
            return 0
        
        left = self.helper(root.left)
        right = self.helper(root.right)
        self.result = max(self.result, root.val + max(left, 0) + max(right, 0))
        return max(left, right, 0) + root.val

5. Divide and Conquer

分治三步: Divide把问题分成较小同类子问题;Conquer递归求解并处理基例;Combine把子结果合成当前结果。时间分析应同时包含递归子问题和合并成本。

整理参考资料