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

剑指 Offer 34. 二叉树中和为某一值的路径(Java)(中等)

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

剑指 Offer 34. 二叉树中和为某一值的路径(Java)(中等)

题目描述:

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

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

示例 1:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]

提示:

树中节点总数在范围 [0, 5000] 内
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000

思路:

回溯

class Solution {
    linkedList> result = new linkedList<>();
    linkedList path = new linkedList<>();
    public List> pathSum(TreeNode root, int target) {
        backtrack(root, target);
        return result;
    }
    void backtrack(TreeNode node, int target) {
        if(node == null) {
            return;
        }
        path.add(node.val);
        if(node.left == null && node.right == null) {
            int sum = 0;
            for(int i = 0; i < path.size(); i++) {
                sum = sum + path.get(i);
            }
            if(sum == target)result.add(new linkedList(path));
            //值得注意的是,记录路径时若直接执行 result.add(path)象加入了 res ;后续 path 改变时, res 中的 path 对象也会随之改变。
            //正确做法:result.add(new linkedList(path)),相当于复制了一个 path 并加入到 res。
        }
        // target = target - node.val;
        // if(target == 0 && node.left == null && node.right == null)result.add(new linkedList(path));
        backtrack(node.left, target);
        backtrack(node.right, target);
        //回溯的关键
        path.remove(path.size() - 1);
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/697735.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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