offer_57
概要:二叉树中和为某一值的路径
题目描述
输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:
)
图片
参考
https://blog.csdn.net/zhangvalue/article/details/95791787
代码实现:
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>> res = new ArrayList<ArrayList<Integer>>();
//中间进行临时变换的
ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
//用前序遍历,每次都先看根节点的值,通过和目标值进行相减,最后为0 的才能加入到res最终答案集合中
//如果不是0 就 递归进行
//递归完了,不管最后得到的答案是否符合,都要把list最后一个值给删掉,然后再返回的上一层
if(root == null) return new ArrayList<ArrayList<Integer>>();//如果当前结点是空,就返回 空的集合
//如果当前结点不是空
list.add(root.val);//把当前结点的值放进list中
target = target - root.val;//用目标值进行相减
if(target == 0 && root.left == null && root.right == null){//如果减到最后target=0了,并且是叶节点
res.add(new ArrayList(list));//就把当前这个list集合装进res中,注意,这个地方要新建一个集合放list中的值。每次都是这样
}
//向左递归
FindPath(root.left,target);
//向右递归
FindPath(root.right,target);
//不管怎么样都一定要把最后加进list中的值给删掉,然后再返回到上一层
list.remove(list.size()-1);
//返回得到的路径
return res;
}
}
总结
前序遍历的特点就是根节点优先,然后判断叶节点。