All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0101_0200.s0112_path_sum.Solution Maven / Gradle / Ivy

There is a newer version: 1.24
Show newest version
package g0101_0200.s0112_path_sum;

// #Easy #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree #Data_Structure_I_Day_12_Tree
// #2022_06_23_Time_0_ms_(100.00%)_Space_43.8_MB_(36.11%)

import com_github_leetcode.TreeNode;

/*
 * 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;
 *     }
 * }
 */
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        if (sum == root.val && root.left == null && root.right == null) {
            return true;
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy