Algorithms first
路径总和 · 交互式算法学习
判断是否存在根到叶路径和等于 target。
#112 · 二叉树
路径总和
Path Sum
root = [5,4,8,11,null,13,4,7,2,null,null,null,1], target = 22树 / 图3 个关键状态
步骤 1经过 5,剩余 17。
target=17推荐
递减剩余目标
时间
O(n)空间 O(h)进入节点就从 target 减去节点值,叶子检查是否刚好为零。
1function hasPathSum(root, target) {2 if (!root) return false;3 if (!root.left && !root.right) return target === root.val;4 return hasPathSum(root.left, target - root.val) || hasPathSum(root.right, target - root.val);5}多语言参考
来源 · CC BY-SA 4.0 ↗Java · C++ · Go
这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。
1/**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode() {}8 * TreeNode(int val) { this.val = val; }9 * TreeNode(int val, TreeNode left, TreeNode right) {10 * this.val = val;11 * this.left = left;12 * this.right = right;13 * }14 * }15 */16class Solution {17 public boolean hasPathSum(TreeNode root, int targetSum) {18 return dfs(root, targetSum);19 }20 21 private boolean dfs(TreeNode root, int s) {22 if (root == null) {23 return false;24 }25 s -= root.val;26 if (root.left == null && root.right == null && s == 0) {27 return true;28 }29 return dfs(root.left, s) || dfs(root.right, s);30 }31}交互式算法学习
从执行步骤真正理解 LeetCode 经典 150
本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。
AlgoViz Lab
路径总和 · 解法对比
判断是否存在根到叶路径和等于 target。
- 测试用例
root = [5,4,8,11,null,13,4,7,2,null,null,null,1], target = 22- 题目分类
- 二叉树
- 解法对比
- 2
枚举所有根叶路径
DFS 保存当前路径,到叶子时求和比较。
- 时间
O(n)- 空间
O(n)
递减剩余目标
进入节点就从 target 减去节点值,叶子检查是否刚好为零。
- 时间
O(n)- 空间
O(h)