二叉树指定路径和

来源:互联网 发布:淘宝账号已被冻结 编辑:程序博客网 时间:2024/05/16 08:00

问题:
给定一个二叉树,找出所有路径中各节点相加总和等于给定目标值target的路径。
一个有效的路径,指的是从根节点到叶节点的路径。

方法:
1、遍历方法:先序遍历
2、判断条件:叶节点的值是否满足要求

代码实现:

/** * 方法一:每次递归生成一个新的List *  * @param p * @param sum * @param path * @param allPath */void getSumPath(TreeNode p, int sum, List<Integer> path, List<List<Integer>> allPath) {    if (p != null) {        if (p.left == null && p.right == null && p.val == sum) {            path.add(p.val);            allPath.add(path);        }        if (p.left != null) {            List<Integer> newPath = new ArrayList<>(path);            newPath.add(p.left.val);            getSumPath(p.left, sum - p.val, newPath, allPath);        }        if (p.right != null) {            List<Integer> newPath = new ArrayList<>(path);            newPath.add(p.right.val);            getSumPath(p.right, sum - p.val, newPath, allPath);        }    }}
/** * 方法二:借助栈结构 *  * @param p * @param sum * @param path * @param allPath */void getSumPath2(TreeNode p, int sum, Stack<Integer> path, List<List<Integer>> allPath) {    if (p != null) {        path.push(p.val);        if (p.left == null && p.right == null && p.val == sum) {            List<Integer> list = new ArrayList<>(path);            allPath.add(list);        }        if (p.left != null) {            getSumPath2(p.left, sum - p.val, path, allPath);        }        if (p.right != null) {            getSumPath2(p.right, sum - p.val, path, allPath);        }        path.pop();    }}