二叉树中和为某一值的路径
话不多说先上代码
import java.util.ArrayList;
public class Findpath {
//树节点
private static class TreeNode{
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int x){
this.val=x;
}
}
public static ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
//最后总结果
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if(root == null){
return result;
}
//子路径
ArrayList<Integer> path = new ArrayList<>();
find(root,target,result,path);
return result;
}
private static void find(TreeNode root,int target,ArrayList<ArrayList<Integer>> result,ArrayList<Integer> path) {
if (root == null) {
return;
}
//先将第一个节点的值加进链表
path.add(root.val);
//用目标值减去该节点的值
target -= root.val;
if(target < 0){
return ;
}
if(target == 0 && root.left == null &&root.right == null){
result.add(path);
return;
}
//递归遍历
find(root.left,target,result,new ArrayList<>(path));
find(root.right,target,result,new ArrayList<>(path));
}
public static void main(String[] args){
TreeNode node10 = new TreeNode(10);
TreeNode node5 = new TreeNode(5);
TreeNode node12 = new TreeNode(12);
TreeNode node7 = new TreeNode(7);
node10.left = node12;
node10.right = node5;
node5.right = node7;
ArrayList<ArrayList<Integer>> res = FindPath(node10, 22);
for (ArrayList<Integer> path : res){
System.out.println(path);
}
}
}
本质上就是深度优先遍历
时间复杂度:O(n), 树的所有节点需要遍历一次
空间复杂度:O(n), 当树退化到链表时,递归空间为O(n)