博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode] Path Sum II
阅读量:4683 次
发布时间:2019-06-09

本文共 2240 字,大约阅读时间需要 7 分钟。

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:

Given the below binary tree and sum = 22,

5             / \            4   8           /   / \          11  13  4         /  \    / \        7    2  5   1

return

[   [5,4,11,2],   [5,8,4,5]]

 

思路:要输出所有结果,dfs枚举。

class Solution {    public List
> pathSum(TreeNode root, int sum) { List
> result = new ArrayList<>(); List
tmp = new ArrayList<>(); pathSumHelper(root,tmp,result,sum); return result; } private void pathSumHelper(TreeNode root, List
tmp, List
> result, int sum){ if(root == null) return; if(root.left==null && root.right==null && root.val == sum){ tmp.add(root.val); result.add(new ArrayList
(tmp)); tmp.remove(tmp.size()-1); return; } tmp.add(root.val); pathSumHelper(root.left,tmp,result,sum-root.val); pathSumHelper(root.right,tmp,result,sum-root.val); tmp.remove(tmp.size()-1); } }

 

 

 第三遍记录:最好采用第二遍的方法,在叶子节点的时候就判断是否满足条件,但是注意此时该节点并未加入到tmp中去,所以需要tmp中先加入root.val,然后 res中添加tmp,最后tmo中的root.val要删掉。

如果在叶子节点的子节点,null节点判断(此时判断n==0即可),但是左右null节点都会满足条件而产生两边结果。

以下方法会有重复元素

import java.util.ArrayList;import java.util.List;public class Solution {    public List
> pathSum(TreeNode root, int sum) { List
> res = new ArrayList
>(); if (root == null) return res; List
tmp = new ArrayList
(); pathSumHelper(root, sum, res, tmp); return res; } private void pathSumHelper(TreeNode root, int sum, List
> res, List
tmp) { if (root == null) { if (sum == 0) res.add(new ArrayList
(tmp)); return; } tmp.add(root.val); pathSumHelper(root.left, sum - root.val, res, tmp); pathSumHelper(root.right, sum - root.val, res, tmp); tmp.remove(tmp.size() - 1); } public static void main(String[] args) { TreeNode root = new TreeNode(5); root.left = new TreeNode(4); root.left.left = new TreeNode(11); root.right = new TreeNode(8); root.right.right = new TreeNode(7); System.out.println(new Solution().pathSum(root, 20)); }}

 

 

 

 

 

转载于:https://www.cnblogs.com/jdflyfly/p/3821437.html

你可能感兴趣的文章
ACM数论-素数
查看>>
Codeforces Round #464 (Div. 2) B. Hamster Farm[盒子装仓鼠/余数]
查看>>
例4-6
查看>>
Vue学习【第四篇】:Vue 之webpack打包工具的使用
查看>>
Python_pip_02_利用pip安装模块(以安装pyperclip为例)
查看>>
触屏智能手机界面可用性要素的纵贯式研究
查看>>
intent(2、隐形intent)
查看>>
JNA 备注
查看>>
vmware Linux虚拟机挂载共享文件夹
查看>>
argument 1 must be 2-item sequence, not int
查看>>
一个基本的MVC模式的增删改查
查看>>
Java开发环境安装过程
查看>>
C++ 利用栈解决运算问题
查看>>
Trie树
查看>>
__attribute__
查看>>
HTML中图像代替提交按钮
查看>>
jquery ajax contentType为application/json
查看>>
Python异常处理
查看>>
FD.io了解
查看>>
RIPng
查看>>