力扣437. 路径总和 III(先序遍历)

437. 路径总和 III - 力扣(LeetCode) (leetcode-cn.com)

 

class Solution {
    int res = 0;
    public int pathSum(TreeNode root, int targetSum) {
        if(root==null){
            return 0;
        }
        inorder(root,targetSum);
        return res;
    }
    public void inorder(TreeNode root,int targetSum){
        if(root==null){
            return;
        }
        rootsum(root,targetSum);
        inorder(root.left,targetSum);
        inorder(root.right,targetSum);
    }

    public void rootsum(TreeNode root,int targetSum){
        if(root==null){
            return;
        }
        if(root.val==targetSum){
            res++;
        }
        rootsum(root.left,targetSum-root.val);
        rootsum(root.right,targetSum-root.val);
    }
}

inorder是递归版的先序遍历

rootsum是求root节点下的所有节点相加是不是等于targetsum

你可能感兴趣的:(力扣,leetcode,算法,java)