zoukankan      html  css  js  c++  java
  • 面试题 04.12. 求和路径

     方法一:暴力搜索

    class Solution {
        private int res = 0;
        public int pathSum(TreeNode root, int sum) {
            order(root,sum);
            return res;
        }
    
        public void order(TreeNode root,int sum) {
            if(root == null) return ;
            dfs(root,sum);
            order(root.left,sum);
            order(root.right,sum);
            
        }
    
        public void dfs(TreeNode root, int sum) {
            if(root == null) return;
            if(sum - root.val == 0) res++;
            dfs(root.left,sum - root.val);
            dfs(root.right,sum - root.val);
        }
    }

    方法二:记录每个节点的前缀和

    class Solution {
    
        public int pathSum(TreeNode root, int sum) {
            
            Map<Integer,Integer> map = new HashMap<>();  // 存放每个节点的前缀和,即之前所有父节点的和
            map.put(0,1); // 到根节点的情况
            return helper(root, map, sum, 0);
        }
    
        public int helper(TreeNode root, Map<Integer,Integer> map, int sum, int curSum) {
            if(root == null) return 0;
    
            curSum += root.val;
            int count = map.getOrDefault(curSum-sum,0); // 如果节点a的前缀和为curSum-sum那么节点a到当前节点的和为sum
    
            map.put(curSum,map.getOrDefault(curSum,0)+1); // 本层前缀和会影响下一层的判断,进入下一层要加入map
            count += helper(root.left,map,sum,curSum);
            count += helper(root.right,map,sum,curSum);
            map.put(curSum,map.get(curSum)-1); // 本层节点前缀和和上一层的没有关系,返回上一层时要移除掉
            return count;
        }
    
    }
  • 相关阅读:
    PAT (Basic Level) Practise 1013 数素数
    PAT (Basic Level) Practise 1014 福尔摩斯的约会
    codeforces 814B.An express train to reveries 解题报告
    KMP算法
    rsync工具
    codeforces 777C.Alyona and Spreadsheet 解题报告
    codeforces 798C.Mike and gcd problem 解题报告
    nginx + tomcat多实例
    MongoDB副本集
    指针的艺术(转载)
  • 原文地址:https://www.cnblogs.com/yonezu/p/13324770.html
Copyright © 2011-2022 走看看