剑指offer——二叉树中和为某一值的路径
2017-04-19 18:51
267 查看
题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。思路:使用先序遍历树,判定如果为叶子节点,则执行判定和是否为target,如果是就加入进去。
传的时候list是引用,所以如果直接加入,它的左右孩子节点往list加是对同一块区域加。
所以这里要写一个clone函数。
import java.util.ArrayList; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { ArrayList<ArrayList<Integer>>alllist = new ArrayList<>(); ArrayList<Integer>list = new ArrayList<>(); if(root==null) return alllist; preorder(root,target,alllist,list,0); return alllist; } public void preorder(TreeNode root,int target,ArrayList<ArrayList<Integer>>alllist,ArrayList<Integer> list,int count){ if(root!=null)list.add(root.val); if(root.left!=null){ preorder(root.left, target, alllist, clone(list), count+root.val); } if(root.right!=null){ preorder(root.right, target, alllist, clone(list), count+root.val); } if(root.left==null&&root.right==null&&count+root.val==target){ alllist.add(list); } } public ArrayList<Integer> clone(ArrayList<Integer> list){ ArrayList<Integer> cList = new ArrayList<>(); for(Integer i:list){ cList.add(i); } return cList; } }
下面的代码思路一样,就是没有写clone函数,直接在那里new了一个:
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<ArrayList<Integer>> paths=new ArrayList<ArrayList<Integer>>();
if(root==null)return paths;
find(paths,new ArrayList<Integer>(),root,target);
return paths;
}
public void find(ArrayList<ArrayList<Integer>> paths,ArrayList<Integer> path,TreeNode root,int target){
path.add(root.val);
if(root.left==null&&root.right==null){
if(target==root.val){
paths.add(path);
}
return;
}
ArrayList<Integer> path2=new ArrayList<>();
path2.addAll(path);
if(root.left!=null)find(paths,path,root.left,target-root.val);
if(root.right!=null)find(paths,path2,root.right,target-root.val);
}
}
相关文章推荐
- 【剑指Offer面试编程题】题目1368:二叉树中和为某一值的路径--九度OJ
- 剑指Offer之二叉树中和为某一值的路径
- 剑指offer 25 二叉树中和为某一值的路径
- 剑指offer — 二叉树中的某一路径
- 剑指offer——面试题25:二叉树中和为某一值的路径
- 剑指offer代码解析——面试题25二叉树中和为某一值的路径
- 剑指Offer----面试题25:二叉树中和为某一值的路径
- 剑指offer:二叉树中和为某一值的路径
- 【剑指Offer面试编程题】题目1368:二叉树中和为某一值的路径--九度OJ
- 【剑指Offer】面试题25:二叉树中和为某一值的路径
- 剑指Offer:面试题25——二叉树中和为某一值的路径(java实现)
- 剑指offer-4-面试25:二叉树中和为某一值的路径
- 【剑指offer】4.3举例让抽象问题具体化——面试题25:二叉树中和为某一值的路径
- 剑指Offer 25题 二叉树中和为某一值的路径 Java
- 剑指Offer之面试题25:二叉树中和为某一值的路径
- 剑指offer_24_二叉树中和为某一值的路径
- 剑指Offer_24_二叉树中和为某一值的路径
- 剑指offer代码解析——面试题25二叉树中和为某一值的路径
- 剑指offer-二叉树中和为某一路径的和
- 二叉树中和为某一值的路径(剑指offer25)