zoukankan      html  css  js  c++  java
  • 0437. Path Sum III (M)

    Path Sum III (M)

    题目

    You are given a binary tree in which each node contains an integer value.

    Find the number of paths that sum to a given value.

    The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

    The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

    Example:

    root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
    
          10
         /  
        5   -3
       /     
      3   2   11
     /    
    3  -2   1
    
    Return 3. The paths that sum to 8 are:
    
    1.  5 -> 3
    2.  5 -> 2 -> 1
    3. -3 -> 11
    

    题意

    在给定的树中找到一条从上到下的路径,使其和为给定值。路径的起点和终点可以是任意结点。

    思路

    双重递归。第一重递归确定根结点,限制需要查找的子树;第二重递归在该子树中找到从子树根结点出发和为sum的路径的个数。


    代码实现

    Java

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        public int pathSum(TreeNode root, int sum) {
            if (root == null) {
                return 0;
            }
            return findPath(root, 0, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
        }
    
        private int findPath(TreeNode root, int curSum, int sum) {
            if (root == null) {
                return 0;
            }
            curSum += root.val;
            return (curSum == sum ? 1 : 0) + findPath(root.left, curSum, sum) + findPath(root.right, curSum, sum);
        }
    }
    
  • 相关阅读:
    使用iText 7读取PDF文件中的文本和图片
    登记或取消登记盈亏库存日记账行数量
    uni-app(未完)
    javaScript的基本优雅写法
    ModuleFederation-模块联邦
    typescript
    img标签src图片路径根目录问题
    开源工具分享
    软件缺陷的度量、分析和统计
    MIT6.824 2020 Lab2 A Raft Leader Election
  • 原文地址:https://www.cnblogs.com/mapoos/p/13461832.html
Copyright © 2011-2022 走看看