Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2022-10-04 09:52:42
112. Path Sum
说明:
给予一个二元树和一个数字target,从root到叶节点的路径称为path,若存在任意path中
所有数字和等于target返回true,否则返回false。
Example 1:
https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.
解法:
1.DFS中序遍历并更新targetSum的值
2.若root是叶子节点且等于targetSum返回true
Java Code:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null) return false;
if(targetSum == root.val && root.left == null && root.right == null)
return true;
return hasPathSum(root.left, targetSum - root.val) ||
hasPathSum(root.right, targetSum - root.val);
}
}
树 = 温柔善良
作者: twosheep0603 (两羊)   2022-10-04 09:58:00
好像大学计程上机考会出现的题目
作者: PyTorch (屁眼火炬)   2022-10-04 10:17:00
大师
作者: pandix (面包屌)   2022-10-04 10:28:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com