标签:tor elements bsp struct 顺序 exception data tin order
题目描述
1 //因为如果放在里面的话每次递归的时候就会重新new一个res和list,这样会把上一步的结果覆盖 2 private static ArrayList<Integer> list = new ArrayList<>(); 3 private static ArrayList<ArrayList<Integer>> res = new ArrayList<>(); 4 public static ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) { 5 if (root == null) { 6 return res; 7 } 8 //不可以设置中间变量,在递归中不正确 9 target -= root.val; 10 //先判断再加入 11 if (target >= 0) { 12 list.add(root.val); 13 if (target == 0 && root.left == null && root.right == null) { 14 //查看源码可知此处创建的对象复制了list中本就存在的元素 15 res.add(new ArrayList<Integer>(list)); 16 } 17 FindPath(root.left, target); 18 FindPath(root.right, target); 19 //弹出结点,每一轮递归返回到父结点时,当前路径也应该回退一个结点 20 list.remove(list.size() - 1); 21 } 22 return res; 23 }
源码解析:new ArrayList<Integer>(list)
1 /** 2 * Constructs a list containing the elements of the specified 3 * collection, in the order they are returned by the collection‘s 4 * iterator.
5 * 构造包含指定集合的元素的列表,按集合的迭代器返回这些元素的顺序
6 * @param c 要将其元素放入此列表中的集合 7 * @throws NullPointerException if the specified collection is null 8 */ 9 public ArrayList(Collection<? extends E> c) { 10 elementData = c.toArray(); 11 if ((size = elementData.length) != 0) { 12 // c.toArray might (incorrectly) not return Object[] (see 6260652) 13 if (elementData.getClass() != Object[].class) 14 elementData = Arrays.copyOf(elementData, size, Object[].class); 15 } else { 16 // replace with empty array. 17 this.elementData = EMPTY_ELEMENTDATA; 18 } 19 }
初始化:
1 public static class TreeNode{ 2 int val=0; 3 TreeNode left=null; 4 TreeNode right=null; 5 public TreeNode(int val){ 6 this.val=val; 7 } 8 } 9 public static TreeNode createBinTree(int[] array) { 10 nodeList=new LinkedList<TreeNode>(); 11 // 将一个数组的值依次转换为TreeNode节点 12 for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) { 13 nodeList.add(new TreeNode(array[nodeIndex])); 14 } 15 // 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树 16 for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) { 17 // 左孩子 18 nodeList.get(parentIndex).left = nodeList 19 .get(parentIndex * 2 + 1); 20 // 右孩子 21 nodeList.get(parentIndex).right = nodeList 22 .get(parentIndex * 2 + 2); 23 } 24 // 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理 25 int lastParentIndex = array.length / 2 - 1; 26 // 左孩子 27 nodeList.get(lastParentIndex).left = nodeList 28 .get(lastParentIndex * 2 + 1); 29 // 右孩子,如果数组的长度为奇数才建立右孩子 30 if (array.length % 2 == 1) { 31 nodeList.get(lastParentIndex).right = nodeList 32 .get(lastParentIndex * 2 + 2); 33 } 34 return nodeList.get(0); 35 }
测试:
1 private static List<TreeNode> nodeList = null; 2 public static void main(String[] args) { 3 int[] tree={10,5,12,4,7}; 4 int target=22; 5 TreeNode node = createBinTree(tree); 6 res= FindPath(node, target); 7 System.out.println(res); 8 } 9 输出:[[10, 5, 7], [10, 12]]
标签:tor elements bsp struct 顺序 exception data tin order
原文地址:https://www.cnblogs.com/Blog-cpc/p/12353352.html