剑指offer-二叉树中和为某一值的路径
题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
代码:
- // 二叉树中和为某一值的路径
- /**
- * 题目描述
- * 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
- */
- ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>();
- ArrayList<Integer> current = new ArrayList<>();
- public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
- if (root == null) {
- return arrayList;
- }
- current.add(root.val);
- if (root.left == null && root.right == null) {
- if (!current.isEmpty()) {
- int sum = 0;
- for (int i : current) {
- sum += i;
- }
- if (sum == target) {
- ArrayList<Integer> list = new ArrayList<>(current);
- arrayList.add(list);
- }
- }
- }
- FindPath(root.left, target);
- FindPath(root.right, target);
- current.remove(current.size() - 1);
- return arrayList;
- }
第二种:
链接:https://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca
来源:牛客网
public class Solution { private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>(); private ArrayList<Integer> list = new ArrayList<Integer>(); public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { if(root == null) return listAll; list.add(root.val); target -= root.val; if(target == 0 && root.left == null && root.right == null) listAll.add(new ArrayList<Integer>(list)); FindPath(root.left, target); FindPath(root.right, target); list.remove(list.size()-1); return listAll; }}posted on 2017-08-25 08:53 WenjieWangFlyToWorld 阅读(157) 评论(0) 收藏 举报
浙公网安备 33010602011771号