35、二叉树中和为某一值的路径
2019-10-01 本文已影响0人
GIndoc
题目:输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
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>> result = new ArrayList<ArrayList<Integer>>();
if(root==null) return result;
findPath(result, new ArrayList<Integer>(), root, target, 0);
return result;
}
private void findPath(ArrayList<ArrayList<Integer>> result,
ArrayList<Integer> path,
TreeNode root,
int target,
int current){
current+=root.val;
// 如果当前值大于期望值,则不用进行后续操作了,直接返回父节点
if(current>target){
current-=root.val;
return;
}
path.add(root.val);
// 如果是叶子节点,且当前值等于期望值,则将路径上的点加入结果列表
if(root.left==null && root.right==null){
if(current==target){
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.addAll(path);
result.add(temp);
}
}else{
// 如果有子节点,则递归子节点
if(root.left!=null){
findPath(result, path, root.left, target, current);
}
if(root.right!=null){
findPath(result, path, root.right, target, current);
}
}
// 返回父节点前移除路径上的最后一个节点
path.remove(path.size()-1);
}
}