|
| 1 | +# LeetCode 437. Path Sum III |
| 2 | + |
| 3 | +## Description |
| 4 | + |
| 5 | +You are given a binary tree in which each node contains an integer value. |
| 6 | + |
| 7 | +Find the number of paths that sum to a given value. |
| 8 | + |
| 9 | +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). |
| 10 | + |
| 11 | +The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. |
| 12 | + |
| 13 | +Example: |
| 14 | + |
| 15 | +```py |
| 16 | +root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 |
| 17 | + |
| 18 | + 10 |
| 19 | + / \ |
| 20 | + 5 -3 |
| 21 | + / \ \ |
| 22 | + 3 2 11 |
| 23 | + / \ \ |
| 24 | +3 -2 1 |
| 25 | + |
| 26 | +Return 3. The paths that sum to 8 are: |
| 27 | + |
| 28 | +1. 5 -> 3 |
| 29 | +2. 5 -> 2 -> 1 |
| 30 | +3. -3 -> 11 |
| 31 | +``` |
| 32 | + |
| 33 | +### 思路 |
| 34 | + |
| 35 | +* 二叉树相关的题目很多情况下都需要用到递归来解决。 |
| 36 | +* 根据题意,求使得和为给定数字的种树。不一定要求从根节点开始。 |
| 37 | +* 思考递归这种解题方式时,需要将原问题拆解成更小的子问题,并且假设子问题已经解决。 |
| 38 | +* 二叉树有左子树和右子树,我们假设左右子树的问题已经解决,即已经知道了左右子树可以形成满足条件的种数;那么此时还剩下以当前节点为起始节点可以形成的种数。 |
| 39 | +* 即整颗二叉树可以形成的路径等于给定值的总数 = 必须以 node 节点为开始节点的种数 + node 左子树可以形成的路径数 + node 右子树可以形成的路径树。 |
| 40 | +* 在求解以 node 节点开始的路径和为给定值的种数时候,可以使用 前/中/后 三种遍历方式中的任意一种。 |
| 41 | +* 这里采用中序遍历的一种方式。 |
| 42 | + |
| 43 | + |
| 44 | +```py |
| 45 | +# -*- coding: utf-8 -*- |
| 46 | +# @Author: 何睿 |
| 47 | +# @Create Date: 2020-05-01 17:30:03 |
| 48 | +# @Last Modified by: 何睿 |
| 49 | +# @Last Modified time: 2020-05-01 19:54:16 |
| 50 | + |
| 51 | +# Definition for a binary tree node. |
| 52 | + |
| 53 | + |
| 54 | +class TreeNode: |
| 55 | + def __init__(self, x): |
| 56 | + self.val = x |
| 57 | + self.left = None |
| 58 | + self.right = None |
| 59 | + |
| 60 | + |
| 61 | +class Solution: |
| 62 | + def pathSum(self, root: TreeNode, sum: int) -> int: |
| 63 | + if not root: |
| 64 | + return 0 |
| 65 | + |
| 66 | + return self.sumRoot(root, 0, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum) |
| 67 | + |
| 68 | + def sumRoot(self, root, pre, sum_): |
| 69 | + |
| 70 | + if not root: |
| 71 | + return 0 |
| 72 | + pre += root.val |
| 73 | + |
| 74 | + left = self.sumRoot(root.left, pre, sum_) |
| 75 | + right = self.sumRoot(root.right, pre, sum_) |
| 76 | + |
| 77 | + return (pre == sum_) + left + right |
| 78 | +``` |
0 commit comments