給定一個二叉樹桨吊,找出所有路徑中各節(jié)點相加總和等于給定 目標值 的路徑。一個有效的路徑凤巨,指的是從根節(jié)點到葉節(jié)點的路徑视乐。
代碼:
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
List<List<Integer>> list=new ArrayList<>();
List<Integer> temp=new ArrayList<>();
findPath(root,target,temp,list);
return list;
}
public void findPath(TreeNode root,int target,List<Integer> temp,List<List<Integer>> path)
{
if (root == null)
return;
if (root.left == null && root.right == null) {
if (root.val == target) {
List<Integer> temp2=new ArrayList<>();
temp2.addAll(temp);
temp2.add(root.val);
path.add(temp2);
}
} else {
temp.add(root.val);
findPath(root.left, target - root.val, temp,path);
findPath(root.right, target - root.val, temp,path);
temp.remove(temp.size() - 1);
}
}
}