LeetCode二叉树路径总和
2023-09-11 14:21:44 时间
路径之和
1.1 题目描述
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。叶子节点 是指没有子节点的节点。
1.2 示例
2.1 解题
解题方法:递归进行计算
二叉树从上向下进行递归计算,每遍历一个节点,就用target-root.val。当叶子节点值等于最后一次target-root.val,则存在路径。Java版解题
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {//遍历到叶子节点时,判断最后的target减去前面路径消耗的val等于节点的val
return sum == root.val;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);//多条路径遍历二叉树
}
}
解题结果
相关文章
- Leetcode: Longest Substring with At Least K Repeating Characters
- leetcode Valid Palindrome C++&python 题解
- LeetCode高频题10:正则表达式匹配
- [LeetCode] Text Justification
- LeetCode 199. 二叉树的右视图
- LeetCode搜索二叉树的练习
- 184、【栈与队列】leetcode ——739. 每日温度(C++版本)
- 101、【树与二叉树】leetcode ——617. 合并二叉树:递归法+迭代法(C++版本)
- 100、【树与二叉树】leetcode ——105. 从前序与中序遍历序列构造二叉树+106. 从中序与后序遍历序列构造二叉树(C++版本)
- 94、【树与二叉树】leetcode ——110. 平衡二叉树(C++版本)
- 91、【树与二叉树】leetcode ——559.n叉树的最大深度(递归DFS+迭代BFS)(C++版本)
- 【LeetCode】71. Simplify Path
- 【LeetCode】【Python题解】Reverse Integer
- [LeetCode] 684. Redundant Connection 冗余的连接
- [LeetCode] 654. Maximum Binary Tree 最大二叉树
- [LeetCode] Verify Preorder Serialization of a Binary Tree 验证二叉树的先序序列化
- [LeetCode] 221. Maximal Square 最大正方形
- [LeetCode] 36. Valid Sudoku 验证数独
- [LeetCode] Binary Tree Right Side View 二叉树的右侧视图
- [LeetCode] Partition List 划分链表
- [LeetCode] 129. Sum Root to Leaf Numbers 求根到叶节点数字之和
- LeetCode二叉树的最小深度
- leetcode 64. Minimum Path Sum 最小路径和(中等)