112. 路径总和

112. 路径总和

原题

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root==null){
            return false;
        }
        //到达叶子结点,判断当前节点值是否与targetSum一步步减的值相等
        if(root.left==null&&root.right==null){
            return root.val==targetSum;
        }
        //左子树和右子树dfs
        return hasPathSum(root.left,targetSum-root.val)||hasPathSum(root.right,targetSum-root.val);
    }


}

你可能感兴趣的:(LeetCode刷题,深度优先,算法)