栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Leetcode 113路径总和II offerLast和push有什么区别

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leetcode 113路径总和II offerLast和push有什么区别

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。


提示:

树中节点总数在范围 [0, 5000] 内
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
先看提示,范围5后面6个零,是小于int的

解法一

class Solution {
    List> ret = new linkedList>();
    Deque path = new linkedList();

    public List> pathSum(TreeNode root, int targetSum) {
        dfs(root, targetSum);
        return ret;
    }

    public void dfs(TreeNode root, int targetSum) {
        if (root == null) {
            return;
        }
        path.offerLast(root.val);
        //这里不能换为 path.push(root.val);
        targetSum -= root.val;
        if (root.left == null && root.right == null && targetSum == 0) {
            ret.add(new linkedList(path));
        }
        dfs(root.left, targetSum);
        dfs(root.right, targetSum);
        path.pollLast();
        //这里不能换为path.pop();
    }
}


offerLast和push有什么区别
首先daque是一个队列(逻辑上可以想象为一个双向栈)
offerLast和pollLast是在队列的后面添加删除元素
push和pop是在队列的前面添加删除元素
这题如果改成push和pop,本是5,4,11,2的路径会变成2,11,4,5

解法二

class Solution {
    private List list = new ArrayList<>();
    private List> res = new ArrayList<>();

    public List> pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return res;
        }
        list.add(root.val);
        if (root.left == null && root.right == null && root.val == targetSum) {
            res.add(new ArrayList<>(list));
        }
        pathSum(root.left, targetSum - root.val);
        pathSum(root.right, targetSum - root.val);
        list.remove(list.size() - 1);
        return res;
    }
}

这说明add和remove是在队列后面进行操作
(remove指定了位置)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/775175.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号