树-Path Sum II(指定和,求根到叶子的路径)
来源:互联网 发布:java入门到精通4 pdf 编辑:程序博客网 时间:2024/06/08 16:57
题目:
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]]
思考:
想了大半天,参考了往上的办法,深度优先搜索,先从根节点的左儿子的左儿子...一直到叶子位置,那么这就是第一条路径了,路径和为参数就加入保存路径的list,否则删掉这个叶子,查看这个节点的兄弟试试看,也就是这个叶子的父节点的有儿子(有的话),采用递归,以此类推。
代码(java):
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> totalPath = new ArrayList<List<Integer>>();int total = 0;List<Integer> currentPath = new ArrayList<Integer>();find(root, sum, currentPath, total, totalPath);return totalPath; } public void find(TreeNode root, int sum, List<Integer> currentPath, int total, List<List<Integer>> totalPath){if(root == null){return;}currentPath.add(root.val);total = total + root.val;if(root.left == null && root.right == null && total == sum){totalPath.add(new ArrayList(currentPath));return;}//首先会一直遍历left,然后才是慢慢的往上走,取查看他的兄弟,所以需要删除最后一个!if(root.left != null){//currentPath.add(root.val);//total = total + root.val;find(root.left, sum, currentPath, total, totalPath);currentPath.remove(currentPath.size() - 1);}if(root.right != null){//currentPath.add(root.val);//total = total + root.val;find(root.right, sum, currentPath, total, totalPath);currentPath.remove(currentPath.size() - 1);}}}
0 0
- 树-Path Sum II(指定和,求根到叶子的路径)
- 求根结点到指定结点的路径
- Path Sum II --路径和(重)
- 寻找树根到叶子的权值之和为sum的路径 Path Sum
- [LeetCode]113. Path Sum II(列出二叉树根到叶路径和等于sum的所有路径)
- LeetCode Path Sum II路径和II
- Path Sum II 路径和II
- 【二叉树】DFS计算路径和,保存路径【113. Path Sum II】【112. Path Sum】
- Path Sum II 计算节点和符合条件的路径
- LeetCode | Path Sum II(路径和2)
- LeetCode OJ 之 Path Sum II (路径和 - 二)
- LeetCode 113. Path Sum II(路径和)
- 找出二叉树所有根到叶子的路径,使得路径和为某一个指定的数字
- 【leetcode 二叉树路径和】Path Sum 和 Path Sum II
- 112. Path Sum | 二叉树到根节点到叶子节点的和
- Tree-----找出和等于给定数字的所有路径(113. Path Sum II)
- 判断二叉树,是否存在一条根到叶子的路径和,与一个指定的目标数字相等
- [Leetcode]113. Path Sum II 求路径和一个数的所有路径
- elastic资料整理
- 数据结构----完全二叉树和满二叉树以及前序、中序、后序遍历
- 使用ThinkPHP框架快速搭建网站(通俗易懂)
- Java 实现导出excel表 POI
- 语义化标签
- 树-Path Sum II(指定和,求根到叶子的路径)
- leetcode笔记—生成最大的 数组Create Maximum Number
- 函数式编程
- java设计模式-组合模式
- Android Home按键的监听与屏蔽方式
- 提交表单用ajax判断登录正确并跳转页面的方法
- POJ 3268Silver Cow Party (迪杰斯特拉)
- 2016.5.25笔记
- C++作业6