246 · 二叉树的路径和 II

246 · 二叉树的路径和 II

方法1:DFS

  • sub的末尾开始往前搜
        List<List<Integer>> res = new ArrayList<>();
        int target;

        public List<List<Integer>> binaryTreePathSum2(TreeNode root, int target) {
            // write your code here
            this.target = target;
            dfs(root, new ArrayList<>());
            return res;
        }


        private void dfs(TreeNode root, List<Integer> sub) {
            if (root == null) return;
            sub.add(root.val);
            int sum = 0;
            for (int i = sub.size() - 1; i >= 0; --i) {
                sum += sub.get(i);
                if (sum == target) res.add(new ArrayList<>(sub.subList(i, sub.size())));
            }
            dfs(root.left, sub);
            dfs(root.right, sub);
            sub.remove(sub.size() - 1);
        }

方法2:DFS

List<List<Integer>> res = new ArrayList<>();
int target;

public List<List<Integer>> binaryTreePathSum2(TreeNode root, int target) {
    this.target = target;
    dfs(root, 0, new ArrayList<>(), false);
    return res;
}

/**
 *
 * @param root
 * @param sum
 * @param path
 * @param needRestart 是否需要断开path,从当前的节点的left 或 right节点开始
 */
private void dfs(TreeNode root, int sum, List<Integer> path, boolean needRestart) {
    //0.出口
    if (root == null) return;
    //1.加入到路径
    sum += root.val;
    path.add(root.val);
    //2.找到目标
    if (sum == target) res.add(new ArrayList<>(path));
    //3.从root节点开始
    dfs(root.left, sum, path, true);
    dfs(root.right, sum, path, true);
    //4.从当前节点的left 或 right节点开始
    if (!needRestart) {
        dfs(root.left,0,new ArrayList<>(),false);
        dfs(root.right,0,new ArrayList<>(),false);
    }
    //5.移除当前节点
    path.remove(path.size()-1);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值