跳至主要內容

437. 路径总和 III

T4mako算法深度优先二叉树小于 1 分钟

437. 路径总和 III

中等

题目描述open in new window

解题思路:
对每个根节点深度遍历

class Solution {
    long res = 0;
    public int pathSum(TreeNode root, long targetSum) {
        if (root == null) return 0;
        path(root,targetSum);
        return (int) res;
    }

    public void path(TreeNode root, long targetSum){
        dfs(root,targetSum,0);
        if(root.left != null) path(root.left,targetSum);
        if (root.right != null) path(root.right,targetSum);
    }

    public void dfs(TreeNode node,long targetSum,long sum){
        sum += node.val;
        if(sum == targetSum) res++;
        if(node.left != null) dfs(node.left,targetSum,sum);
        if(node.right != null) dfs(node.right,targetSum,sum);
    }

}
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.5