本文是根据穷码农的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]
]
此题在上一题的框架基础上,需额外添加一个列表