题目
输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思想
递归
代码
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 {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> path = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null)
return result;
Search(root,target);
return result;
}
void Search(TreeNode root,int target)
{
if(root == null)
return;
if(target - root.val < 0)
return;
if(root.left == null && root.right == null)
{
if(target == root.val)
{
path.add(root.val);
result.add(new ArrayList<>(path));
path.remove(path.size()-1);
}
return;
}
path.add(root.val);
Search(root.left,target-root.val);
Search(root.right,target-root.val);
path.remove(path.size()-1);
}
}