2019.10.22 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
github:https://github.com/ChopinXBP/LeetCode-Babel
二叉树问题一定离不开递归。这题很容易可以想到基础的递归方法:
从每一个结点开始,DFS遍历所有路径
由于存在大量的重复路径,所以也可以考虑将已经计算过的路径值保存在哈希表中,从根节点开始,进行记忆化回溯。
遍历到每一个结点的当前路径长度为curSum,如果之前有路径长度为presum=curSum-target,说明presum至curSum对应结点间必存在一条长度为target的路径。
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.
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
返回 3。和等于 8 的路径有:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
import java.util.HashMap;
/**
*
* 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.
* 给定一个二叉树,它的每个结点都存放着一个整数值。
* 找出路径和等于给定数值的路径总数。
* 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
* 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
*
*/
public class PathSumIII {
public class TreeNode