zoukankan      html  css  js  c++  java
  • 437. Path Sum III

    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,问在树中是否存在一条路径,路径上所有结点之和恰好等于sum。路径不限制一定要开始于根结点或者结束于叶子结点,但是一定要是向下的(从父亲结点向儿子结点)。如果存在这样的路径,求出有多少条

     1     int findPath(TreeNode node, int curSum, int sum) {
     2         if (node == null) return 0;
     3         curSum += node.val;
     4         int sameCount = curSum == sum ? 1 : 0;
     5         return sameCount + findPath(node.left, curSum, sum) + findPath(node.right, curSum, sum);
     6     }
     7     
     8     public int pathSum(TreeNode root, int sum) {
     9 //        以每一个节点作为路径根节点进行前序遍历,查找每一条路径的权值和与sum是否相等
    10         if (root == null) return 0;
    11         int res = findPath(root, 0, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
    12         return res;        
    13     }
  • 相关阅读:
    vue中使用第三方UI库的移动端rem适配方案
    前端规范--eslint standard
    从上往下打印二叉树
    栈的压入,弹出序列
    随机森林
    LR
    顺时针打印矩阵
    包含min函数的栈
    树的子结构
    合并两个有序链表
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7705256.html
Copyright © 2011-2022 走看看