Easy Java Solution


  • 0
    S
    public class Solution {
        private int result = 0;
        public int pathSum(TreeNode root, int sum) {
            if (root == null) return result;
            helper(root, sum, false);
            return result;
        }
        
        private void helper(TreeNode node, int sum, boolean hasParent) {
            if (node == null) return;
            if (node.val == sum) {
                result++;
            }
            helper(node.left, sum - node.val, true);
            if (!hasParent) helper(node.left, sum, false);
            helper(node.right, sum - node.val, true);
            if (!hasParent) helper(node.right, sum, false);
        }
    }
    

  • 1

    @siyiwang

    • Please read the instructions first to format your code properly next time;
    • Please try to use default language to really share thoughts - no Chinese, please.

    Thank you!


  • 0
    S

    It is my first time using this post function here. Sorry about that.
    How can I correct that?


  • 0
    S

    @LHearen Thank you for your instruction.


  • 0

    @siyiwang Did you read the read the instructions at the head of the page? It's about how to properly use the forum to make it better.

    Normally when you try to insert some code, try to use three back quotes ``` to include the code - back quote is just below the esc in the keyboard.

    Good luck and have fun in Leetcode!


Log in to reply
 

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