zoukankan      html  css  js  c++  java
  • [Algo] 141. Binary Tree Path Sum To Target III

    Given a binary tree in which each node contains an integer number. Determine if there exists a path (the path can only be from one node to itself or to any of its descendants), the sum of the numbers on the path is the given target number.

    Examples

        5

      /    

    2      11

         /    

        6     14

      /

     3

    If target = 17, There exists a path 11 + 6, the sum of the path is target.

    If target = 20, There exists a path 11 + 6 + 3, the sum of the path is target.

    If target = 10, There does not exist any paths sum of which is target.

    If target = 11, There exists a path only containing the node 11.

    How is the binary tree represented?

    We use the level order traversal sequence with a special symbol "#" denoting the null node.

    /**
     * public class TreeNode {
     *   public int key;
     *   public TreeNode left;
     *   public TreeNode right;
     *   public TreeNode(int key) {
     *     this.key = key;
     *   }
     * }
     */
    public class Solution {
      public boolean exist(TreeNode root, int target) {
        // Write your solution here
        Set<Integer> set = new HashSet<>();
        set.add(0);
        return helper(root, set, target, 0);
      }
    
      private boolean helper(TreeNode root, Set<Integer> set, int target, int prefixSum) {
        if (root == null) {
          return false;
        }
        int curSum = root.key + prefixSum;
        if (set.contains(curSum - target)) {
          return true;
        }
    
        boolean needRemoval = set.add(curSum);
        boolean left = helper(root.left, set, target, curSum);
        boolean right = helper(root.right, set, target, curSum);
        // it is possible to remove previous presum here, 
        // such as 0, pathsum = 0, cannot check pathsum from root after here
        if (needRemoval) {
          set.remove(curSum);
        }
        return left || right;
      } 
    }
  • 相关阅读:
    注解方式整合mybatis & SpringBoot整合分页助手 & SpringBoot整合JSP
    xml方式整合mybatis
    @SpringBootApplication&多环境配置&引入外部配置信息
    用例图&类图
    OOP特性介绍&域模型&静态建模和动态建模
    Git标签
    Git分支
    zabbix监控es集群健康状态(python2.7)
    Django使用问题记录
    failed to update local proxy configuration copy: unexpected field "hosts.available"解决
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12423533.html
Copyright © 2011-2022 走看看