Share my easy and clean recursion Java solution with explanation

  • 8
    public class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            // check if root is null
            if(root == null) return false;
            // if the current node is not a leaf node, do recursion.
            if(root.left != null || root.right != null) 
                return hasPathSum(root.left, sum - root.val) || 
                    hasPathSum(root.right, sum - root.val);
            // now the current node is a leaf node
            return sum - root.val == 0;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.