FTPrep, 113 Path Sum II

来源:互联网 发布:如何禁止手机安装软件 编辑:程序博客网 时间:2024/06/03 19:11

dfs + BT的套路;

BT套路 标志: 输出是 list in list 形式。

dfs套路 标志: 树的 路径和 问题。

刚刚的代码, 5min,1 time bug-free

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public List<List<Integer>> pathSum(TreeNode root, int sum) {        List<List<Integer>> result = new ArrayList<List<Integer>>();        if(root==null) return result;        List<Integer> item = new ArrayList<Integer>();        dfsAndBT(root, sum, item, result);        return result;    }            private void dfsAndBT(TreeNode root, int sum, List<Integer> item, List<List<Integer>> result){        if(root.left==null && root.right==null && root.val==sum){            item.add(root.val);            result.add(new ArrayList<Integer>(item));            item.remove(item.size()-1);            return;        }        if(root.left!=null){            item.add(root.val);            dfsAndBT(root.left, sum-root.val, item, result);            item.remove(item.size()-1);        }        if(root.right!=null){            item.add(root.val);            dfsAndBT(root.right, sum-root.val, item, result);            item.remove(item.size()-1);        }    }}// 5min, one time bug-free. 还是满满的套路。其实从输出的形式就知道是 backtracking 套路,再加上是在tree里dfs,所以helperfunction的命名可以直接写成两者合并。// 唯一知道注意的点,也是一个关键! 就是 传入helper function的root,已经提前判断好了 (!=null;) 因为你看递归调用的时候 root.left 和 root.right 都是非null的。所以可以在 主function里进行check root==null?



之前的代码:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public List<List<Integer>> pathSum(TreeNode root, int sum) {        List<List<Integer>> result = new ArrayList<List<Integer>>();        if(root==null) return result;        backTracking(result, new ArrayList<Integer>(), root, sum);        return result;    }        private void backTracking(List<List<Integer>> result, List<Integer> item, TreeNode root, int sum){        if(root.left==null && root.right==null && root.val==sum){            item.add(root.val);            result.add(new ArrayList<Integer>(item));            item.remove(item.size()-1);            return ;        }        if(root.left!=null){            item.add(root.val);            backTracking(result, item, root.left, sum-root.val);            item.remove(item.size()-1);        }        if(root.right!=null){            item.add(root.val);            backTracking(result, item, root.right, sum-root.val);            item.remove(item.size()-1);        }    }}// TODO 总结:// 不错!! 第一遍的时候出了个小bug,但是看了一眼之前的代码,只看到了一个地方就修改到正确了,在result.add()时!只能加一个copy,不能加本身!!// 而且你在这里进行了 item.add(); 那么相应的,要在对item进行处理完之后马上进行 remove,回归原来状态!!!// 第二个值得总结的的点,还是老规矩:对两个子树的情况的判断。



类似题型:112,113,还有其他的,todo

原创粉丝点击