剑指offer(24)二叉树中和为某一值的路径

import java.util.ArrayList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/

/*
//按照长度从大到小排出的算法代码,匿名内部类的方式

Collections.Sort(listAll, new Comparator<ArrayList<Integer>>(){
    @Override
    public int Compare(ArrayList<Integer> o1, ArrayList<Integer> o2){
    if(o1 < o2){
    return 1;
    }else{
    return -1;
    }
    }
});


*/
public class Solution {
    //调用自身的递归,必须把这种声明放在方法体外面,否则每次递归都重新定义一遍
         ArrayList<ArrayList<Integer>> listAll = new ArrayList<>();
        ArrayList<Integer> list = new ArrayList<>();
    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<>(list));
        }  
            
            FindPath(root.left, target);
            FindPath(root.right, target);
        list.remove(list.size() - 1);//遍历到叶子节点还未找到则回退到父节点,(深度搜索)
        return listAll;
        
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34403001/article/details/88876670