LeetCode专项练习之树上深度优先搜索(Tree Depth-First Search)笔记

本文记录了作者在LeetCode上进行树的深度优先搜索(DFS)专项练习的心得,包括Path Sum系列、Sum Root to Leaf Numbers、Diameter of Binary Tree和Binary Tree Maximum Path Sum等6道题目。作者强调了递归在解决DFS问题中的重要性,并分享了针对不同题目的解题思路和关键技巧,如避免路径和超出范围、正确处理路径存储和回溯等。
摘要由CSDN通过智能技术生成

本文是根据穷码农的LeetCode刷题建议而进行专项练习时记录的心得。

这一次的训练加强了自己对递归的理解与熟练度,毕竟针对深度优先搜索,我是全部使用递归解决的问题。尽管许多题目我没能完全独立解决,需要解析进行辅助,但针对解析提供的方法我都进行了相对详细的分析,将思路的引导以笔记形式记录了下来,希望能对读者起到帮助。

今天的笔记包含基于树的深度优先搜索(Tree Depth-First Search)类型下的6个题目,它们在leetcode上的编号和题名分别是:

  • 112 - Path Sum
  • 113 - Path Sum II
  • 437 - Path Sum III
  • 129 - Sum Root to Leaf Numbers
  • 543 - Diameter of Binary Tree
  • 124 - Binary Tree Maximum Path Sum

下面将根据以上顺序分别记录代码和对应心得,使用的编译器为Pycharm (Python3)。


Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

这道题我根据前序遍历的思想,遍历完所有节点并在每次循环时对当前节点值进行求和操作。但我一开始的想法是如果当前的和超过了规定值就回退到父节点,经过验证后发现这样做无非是给自己增加难度。根据题目要求,最终的路径必须到达叶节点,那么最直接的办法便是一鼓作求和到叶节点,不符合条件时直接返回False即可,否定这条路径。

class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        # special consideration(s)
        if root is None:
            return False

        # 'parameters'
        # inner recursion function
        def hasSum(node: TreeNode, total_sum: int) -> bool:
            # get the sum
            total_sum = total_sum + node.val

            if not node.right and not node.left:
                return total_sum == sum

            if node.left and node.right:
                return hasSum(node.left, total_sum) or hasSum(node.right, total_sum)
            if node.left:
                return hasSum(node.left, total_sum)
            if node.right:
                return hasSum(node.right, total_sum)

        # start recursion
        return hasSum(root, 0)

Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:
[
   [5,4,11,2],
   [5,8,4,5]
]

此题在上一题的框架基础上,需额外添加一个列表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值