题解 | #二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
二叉树是天然可递归的数据结构
public boolean hasPathSum (TreeNode root, int sum) { // write code here //可能有负数结点,sum可能为任何值 if(root==null)return false; //每次减去已遍历的结点的值 sum-=root.val; //递归终止条件,为叶子结点且累计值为sum if(sum==0&&root.left==null&&root.right==null) return true; //每个结点的左右子结点都分别进入左右两个子树运算,都各自有自己的sum return hasPathSum(root.left,sum)||hasPathSum(root.right,sum); }