You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
当递归调用函数时,发现节点没有左右子节点,说明它是叶子节点,此时就可以对比当前的值是否和传入的目标值 sum 相等,返回结果即可。
lethasPathSum=function(root,sum){if(!root){returnfalse}// 叶子节点 判断当前的值是否等于 sum 即可if(!root.left&&!root.right){returnroot.val===sum}return(hasPathSum(root.left,sum-root.val)||hasPathSum(root.right,sum-root.val))}
The text was updated successfully, but these errors were encountered:
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例:
思路
从第一个节点求是否有路径之和为 22,可以转化为从左节点开始,是否有路径之和为 22 -5 = 18,也可以转化为从右节点开始,是否有路径之和为 22 - 5 = 18。
当递归调用函数时,发现节点没有左右子节点,说明它是叶子节点,此时就可以对比当前的值是否和传入的目标值 sum 相等,返回结果即可。
The text was updated successfully, but these errors were encountered: