在codetop上搜了搜字节的前端,这个居然是出现频率第二的题
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null) return false;
if (root.left == null && root.right == null) return targetSum == root.val;
return hasPathSum(root.left,targetSum-root.val)||hasPathSum(root.right,targetSum-root.val);
}
}
这篇博客讨论了一个在字节跳动前端面试中出现频率极高的问题——如何在树形结构中判断是否存在一条路径,使得路径上的节点值之和等于目标值。给出的解决方案是一个递归函数,通过比较当前节点值与目标值的关系,以及遍历左子树和右子树来寻找可能的路径。
1877

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



