路径总和
- https://leetcode.cn/problems/path-sum/
描述
-
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。
-
叶子节点 是指没有子节点的节点。
示例1
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true
解释:等于目标和的根节点到叶节点路径如上图所示。
示例2
1
/ \
2 3
输入:root = [1,2,3], targetSum = 5
输出:false
解释:树中存在两条根节点到叶子节点的路径:
(1 --> 2): 和为 3
(1 --> 3): 和为 4
不存在 sum = 5 的根节点到叶子节点的路径。
示例2
输入:root = [], targetSum = 0
输出:false
解释:由于树是空的,所以不存在根节点到叶子节点的路径。
提示
- 树中节点的数目在范围 [0, 5000] 内
- -1000 <= Node.val <= 1000
- -1000 <= targetSum <= 1000
Typescript 版算法实现
1 )方案 1
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
if(!root) return false
let res = false;
const dfs = (n: TreeNode | null, v: number) => {
// 在叶子节点处符合题目要求, 则结束递归
if (!n.left && !n.right && v === targetSum) {
res = true;
return;
}
n.left && dfs(n.left, v + n.left.val);
n.right && dfs(n.right, v + n.right.val);
}
dfs(root, root.val)
return res;
}
-
思路
- 深度优先遍历中,记录当前路径的节点值的和
- 在叶子节点处,判断当前路径的节点值的和是否等于目标值
-
步骤
- 深度优先遍历二叉树,在叶子节点处,判断当前路径的节点值的和是否等于目标值,是就返回true
- 遍历结束,如果没有匹配,就返回false
2 )方案 2
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
if (!root) {
return false
}
function process(node: TreeNode, rest: number) {
if (!node.left && !node.right) {
return rest === node.val
}
let isSum = false
if (node.left) {
isSum ||= process(node.left, rest - node.val)
}
if (node.right) {
isSum ||= process(node.right, rest - node.val)
}
return isSum
}
return process(root,targetSum)
};
- 这是官方示例,也是用的递归,深度优先遍历
- 这个只是换了一种累减的思路,同方案1的思路
3 )方案 3
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
if (!root) return false
if(!root.left && !root.right) return root.val == targetSum;
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
};
- 这个是方案2的简洁版
4 )方案 4
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
if(!root) return false
const q:[TreeNode | null, number][] = [[root, root.val]] // 声明一个队列
while (q.length) {
const first = q.shift() // 拿到当前队首元素
const [n, v] = first
if (!n.left && !n.right && v === targetSum) return true // 找到了节点
if (n.left) q.push([n.left, v + n.left.val])
if (n.right) q.push([n.right, v + n.right.val])
}
return false
}
- 这里是官方示例,是python的版本修改而来的
- 这个思想是基于广度优先遍历,使用队列保存遍历到每个节点时的路径和
- 如果该节点恰好是叶子节点,并且路径和正好等于sum,说明找到了解
5 )方案 5
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
if(!root) return false
const stack:[TreeNode | null, number][] = [[root, root.val]] // 声明一个栈
while (stack.length) {
const first = stack.pop() // 拿到当前栈顶元素
const [n, v] = first
if (!n.left && !n.right && v === targetSum) return true // 找到了节点
if (n.left) stack.push([n.left, v + n.left.val])
if (n.right) stack.push([n.right, v + n.right.val])
}
return false
}
- 这个也是官方示例,既然使用dfs深度优先遍历可行,那递归的本质既然是栈
- 我们可以用栈来同时保存节点和到这个节点的路径和
- 只要能把所有的节点访问一遍,那么就一定能找到正确的结果
Python3 版算法实现
1 ) 方案1:深度优先搜索(DFS)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
res = False
def dfs(n: Optional[TreeNode], v: int) -> None:
if not n.left and not n.right and v == targetSum:
nonlocal res
res = True
return
if n.left:
dfs(n.left, v + n.left.val)
if n.right:
dfs(n.right, v + n.right.val)
dfs(root, root.val)
return res
2 )方案2:递归法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
def process(node: Optional[TreeNode], rest: int) -> bool:
if not node.left and not node.right:
return rest == node.val
is_sum = False
if node.left:
is_sum |= process(node.left, rest - node.val)
if node.right:
is_sum |= process(node.right, rest - node.val)
return is_sum
return process(root, targetSum)
3 )方案3:递归法(简化版)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
if not root.left and not root.right:
return root.val == targetSum
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)
4 )方案4:广度优先搜索(BFS)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
q = deque([(root, root.val)])
while q:
n, v = q.popleft()
if not n.left and not n.right and v == targetSum:
return True
if n.left:
q.append((n.left, v + n.left.val))
if n.right:
q.append((n.right, v + n.right.val))
return False
5 )方案5:深度优先搜索(DFS)使用栈
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
stack = [(root, root.val)]
while stack:
n, v = stack.pop()
if not n.left and not n.right and v == targetSum:
return True
if n.left:
stack.append((n.left, v + n.left.val))
if n.right:
stack.append((n.right, v + n.right.val))
return False
Golang 版算法实现
1 ) 方案1:深度优先搜索(DFS)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
res := false
var dfs func(n *TreeNode, v int)
dfs = func(n *TreeNode, v int) {
if n.Left == nil && n.Right == nil && v == targetSum {
res = true
return
}
if n.Left != nil {
dfs(n.Left, v+n.Left.Val)
}
if n.Right != nil {
dfs(n.Right, v+n.Right.Val)
}
}
dfs(root, root.Val)
return res
}
2 )方案2:递归法
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
var process func(node *TreeNode, rest int) bool
process = func(node *TreeNode, rest int) bool {
if node.Left == nil && node.Right == nil {
return rest == node.Val
}
isSum := false
if node.Left != nil {
isSum = isSum || process(node.Left, rest-node.Val)
}
if node.Right != nil {
isSum = isSum || process(node.Right, rest-node.Val)
}
return isSum
}
return process(root, targetSum)
}
3 )方案3:递归法(简化版)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
if root.Left == nil && root.Right == nil {
return root.Val == targetSum
}
return hasPathSum(root.Left, targetSum-root.Val) || hasPathSum(root.Right, targetSum-root.Val)
}
4 )方案4:广度优先搜索(BFS)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
queue := []*TreeNodeWithSum{{root, root.Val}}
for len(queue) > 0 {
n, v := queue[0].Node, queue[0].Sum
queue = queue[1:]
if n.Left == nil && n.Right == nil && v == targetSum {
return true
}
if n.Left != nil {
queue = append(queue, &TreeNodeWithSum{n.Left, v + n.Left.Val})
}
if n.Right != nil {
queue = append(queue, &TreeNodeWithSum{n.Right, v + n.Right.Val})
}
}
return false
}
type TreeNodeWithSum struct {
Node *TreeNode
Sum int
}
5 )方案5:深度优先搜索(DFS)使用栈
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
stack := []*TreeNodeWithSum{{root, root.Val}}
for len(stack) > 0 {
n, v := stack[len(stack)-1].Node, stack[len(stack)-1].Sum
stack = stack[:len(stack)-1]
if n.Left == nil && n.Right == nil && v == targetSum {
return true
}
if n.Left != nil {
stack = append(stack, &TreeNodeWithSum{n.Left, v + n.Left.Val})
}
if n.Right != nil {
stack = append(stack, &TreeNodeWithSum{n.Right, v + n.Right.Val})
}
}
return false
}
type TreeNodeWithSum struct {
Node *TreeNode
Sum int
}
383



被折叠的 条评论
为什么被折叠?



