码农小汪-剑指Offer之22-二叉树中和为某一值的路径

来源:互联网 发布:数据库下载 编辑:程序博客网 时间:2024/05/22 18:55

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
说实话,刚开始真的没有理解这个道理是啥子意思来着,我来讲个通俗易懂的吧!我们从根一直访问到我们的叶子。每个节点加起来的值为我们输入整数的值。另一种说法就是。求解所有到叶子节点的值得和,并打印出所有的路径,这里增加了一些其他的要求!

解题思路

这种问题来说,打印出所有的可能,而且是从根到叶子节点的值,必须的dfs深度优先遍历吧,然后进行处理!dfs处理递归的过程吧!

错误解读

我在处理把一个Arraylist对象的时候没有进行复制,这样那个list的在堆区的地址没有变,我在去修改,那么以前的值就会别覆盖掉啦,所以我要进行复制处理。

代码:

package JianzhiOffer;import java.util.ArrayList;public class Slution22 {    public ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();    public ArrayList<Integer> tempList = new ArrayList<Integer>();    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int value) {        if (root == null) {            return list;        }        dfs(root, value);        return list;    }    /**     * 深度优先遍历     *      * @param root     * @param value     */    public void dfs(TreeNode root, int value) {        if (root == null) {            return;        }        tempList.add(root.val);        if (root.left == null && root.right == null) {            if (root.val == value) {                list.add((ArrayList<Integer>) tempList.clone());            }        } else {            if (root.left != null) {                dfs(root.left, value - root.val);            }            if (root.right != null) {                dfs(root.right, value - root.val);            }        }        /**         * 应为这个tempList是个全局的list 这里的意思就是,当我们达到叶子节点之后,不管满足不满足都会把当前的元素         * 踢掉,这个就是我们记录元素路径的东西。 因为深度优先遍历,是把这个所有的记录都会遍历一遍,肯定会包含所有的从根到叶子节点         * 的值为value的结果的!         */        tempList.remove(tempList.size() - 1);    }}

高手解读,使用剪纸技术,相当的厉害

剪纸,意思就是减少我们遍历的次数直接的影响我们的响应时间!
这种思想非常的不错,因为当我们的和相加之后大于了,目的值,没必要进行下面的子树了。或者当我们值得结果小于零了之后,下面的肯定不对(我进行value-root.val….)

public class Solution {    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {        ArrayList<ArrayList<Integer>> re = new ArrayList<ArrayList<Integer>>();        if (root == null) {            return re;        }        dfs(root, target, re, new ArrayList<Integer>(), 0);        return re;    }    void dfs(TreeNode root, int target, ArrayList<ArrayList<Integer>> re,            ArrayList<Integer> item, int sum) {        if (root == null) {            return;        }        item.add(root.val);        sum += root.val;        if (root.left == null && root.right == null) {            if (sum == target) {                re.add((ArrayList<Integer>) item.clone());            }        } else {            if (sum >= target) {// 剪枝            } else {                dfs(root.left, target, re, item, sum);                dfs(root.right, target, re, item, sum);            }        }        item.remove(item.size() - 1);        sum -= root.val;    }}
0 0
原创粉丝点击