LeetCode -- Path Sum III分析及实现方法
作者:lqh 发布时间:2022-10-16 13:41:14
标签:LeetCode,Path,Sum
LeetCode -- 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.
给定一个二叉树,遍历过程中收集所有可能路径的和,找出和等于X的路径树。
思路:
设当前节点为root,分别收集左右节点路径和的集合,merge到当前集合中;
将当前节点添加到数组中,构成新的可能路径。
实现代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int _sum;
private int _count;
public int PathSum(TreeNode root, int sum)
{
_count = 0;
_sum = sum;
Travel(root, new List<int>());
return _count;
}
private void Travel(TreeNode current, List<int> ret){
if(current == null){
return ;
}
if(current.val == _sum){
_count ++;
}
var left = new List<int>();
Travel(current.left, left);
var right = new List<int>();
Travel(current.right, right);
ret.AddRange(left);
ret.AddRange(right);
for(var i = 0;i < ret.Count; i++){
ret[i] += current.val;
if(ret[i] == _sum){
_count ++;
}
}
ret.Add(current.val);
//Console.WriteLine(ret);
}
}
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
来源:http://blog.csdn.net/lan_liang/article/details/55826872
0
投稿
猜你喜欢
- 一、前言null与NULL不都是表示空值吗?这有什么值得深入讨论的的?首先你在编写Java代码时使用过NULL吗?大概用IDE用习惯了,自动
- Spring Cloud Gateway使用Spring Cloud Gateway是一个基于Spring Boot 2.x和Spring&
- 1. maven项目导入idea报ComponentLookupException异常1.1. 问题描述最近将IDEA 升级到 Intell
- 前言本文主要讲述如何使用Java + FFmpeg实现对视频文件的信息提取、码率压缩、分辨率转换等功能;之前在网上浏览了一大圈Java使用F
- 笔者计划为大家介绍分布式文件系统,用于存储应用的图片、word、excel、pdf等文件。在开始介绍分布式文件系统之前,为大家介绍一下使用本
- 1.概述Spring MVC是Spring Framework的一部分,是基于Java实现MVC的轻量级Web框架。Spring MVC的特
- 传统的web项目,只需要在web.xml里配置多个即可,并且支持多个url-pattern在spring boot中,我们默认无需配置,系统
- 概要本节要实现的是多表关联查询的简单demo。场景是根据id查询某商品分类信息,并展示该分类下的商品列表。一、Mysql测试数据新建表Cat
- Java中List.of()和Arrays.asList()的区别及原因动手写一下,让自己更有印象1.Arrays.asList()可以插入
- spring.thymeleaf.cache=false不起作用配置是清除缓存,实现热部署。也就是修改了html后不用重启,刷新页面就能看到
- 一、C#对XML格式数据的解析1、用XMLDocument来解析XmlDocument xmlDocument = new XmlDocum
- 0.关于AOP面向切面编程(也叫面向方面编程):Aspect Oriented Programming(AOP),是软件开发中的一个热点,也
- Spring 中bean的获取1.通过context.getbean 的方式来获取beanApplicationContext:是sprin
- 1.MyBatis中map的应用1.1.应用场景假设,实体类,或者数据库中的表,字段或者参数过多,应当考虑使用Map!!!1.2.具体实现/
- 一、Java类加载机制1.概述 Class文件由类装载器装
- SSM+redis整合ssm框架之前已经搭建过了,这里不再做代码复制工作。这里主要是利用redis去做mybatis的二级缓存,mybait
- 顺序语句顺序顾名思义就是程序自上而下执行public class User { public static voi
- 前言本文的记录如何用CustomPaint、GestureDetector实现一个进度条控件。首先需要说明的是 flutter Materi
- 前言出去面试的时候,对java的集合框架考察的知识点还是蛮多的。除了基础的集合常见API使用,对集合底层的实现原理以及数据结构等也有很多考察
- 在Java里面,可以用复制语句”A=B”给基本类型的数