题目描述
输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
ArrayList<ArrayList<Integer>> res=new ArrayList<>();
int sum=0;
Stack<Integer> s=new Stack<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root==null)return res;
path(root,target);
return res;
}
void path(TreeNode root,int target){
if(root==null)return;//不加会出现空指针异常
if(root.left==null&&root.right==null){
if(sum==target-root.val){
ArrayList<Integer> al=new ArrayList<>();
for(int i=0;i<s.size();i++){
al.add(s.elementAt(i));
}
al.add(root.val);
res.add(al);
}
return;
}
s.push(root.val);
sum+=root.val;
path(root.left,target);
path(root.right,target);
sum-=root.val;
s.pop();
return;
}
}
对上述做改进:
只需对ArrayList做数据增删即可,无需引入额外数据结构stack
import java.util.ArrayList;
public class Solution {
ArrayList<ArrayList<Integer>> res=new ArrayList<>();
ArrayList<Integer> al=new ArrayList<>();
int sum=0;
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
path(root,target);
return res;
}
public void path(TreeNode root,int target){
if(root==null)return;
if(root.left==null&&root.right==null){
if(sum+root.val==target){
al.add(root.val);
res.add(new ArrayList<Integer>(al));
al.remove(al.size()-1);
}
return;
}
sum+=root.val;
al.add(root.val);
path(root.left,target);
path(root.right,target);
sum-=root.val;
al.remove(al.size()-1);
return;
}
}
剑指offer第2版P183
直接对原函数作递归,并增设两个if判断,以防只有一个孩子的节点
public class Solution {
ArrayList<ArrayList<Integer> > res=new ArrayList<>();
ArrayList<Integer> al=new ArrayList<>();
int sum=0;
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root==null)return res;
if(root.left==null&&root.right==null){
if(root.val+sum==target){
al.add(root.val);
res.add(new ArrayList<Integer>(al));
al.remove(al.size()-1);
}
return res;
}
sum+=root.val;
al.add(root.val);
if(root.left!=null){
FindPath(root.left,target);
}
if(root.right!=null){
FindPath(root.right,target);
}
sum-=root.val;
al.remove(al.size()-1);
return res;
}
}