zoukankan      html  css  js  c++  java
  • leetcode437--Path Sum III

    https://leetcode.com/problems/path-sum-iii/

    理解比较困难,可以先看https://www.cnblogs.com/albert67/p/10416402.html

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int pathSum(TreeNode root, int sum) {
            HashMap<Integer,Integer> preSum=new HashMap<>();
            preSum.put(0,1);// 当键值等于0,说明curSum==sum,所以把设为1
            return helper(root,0,sum,preSum);
        }
        
        public int helper(TreeNode n,int curSum,int target,HashMap<Integer,Integer> preSum){
            if(n==null)return 0;
            curSum+=n.val;
            int res=preSum.getOrDefault(curSum-target,0);
            preSum.put(curSum,preSum.getOrDefault(curSum,0)+1);
            res+=helper(n.left,curSum,target,preSum)+helper(n.right,curSum,target,preSum);
            preSum.put(curSum,preSum.get(curSum)-1);
            return res;
        }
    }

    递归比较慢,但很容易理解

    class Solution {
        public int pathSum(TreeNode root, int sum) {
            if(root==null)return 0;
            return add(root,sum)+pathSum(root.left,sum)+pathSum(root.right,sum);
        }
        public int add(TreeNode n,int sum){
            if(n==null)return 0;
            return (sum-n.val==0?1:0)+add(n.left,sum-n.val)+add(n.right,sum-n.val);
        }
        
    }
  • 相关阅读:
    js:鼠标事件
    js:argument
    js:|| 和 && 运算符 特殊用法
    css:选择器
    css:清除浮动 overflow
    jquery:after append appendTo三个函数的区别
    WIndow Document
    css:颜色名和十六进制数值
    安装centos出错
    Leetcode | Unique Paths I & II
  • 原文地址:https://www.cnblogs.com/albert67/p/10416569.html
Copyright © 2011-2022 走看看