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

8.<tag-二叉树和回溯>lt.112. 路径总和

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

8.<tag-二叉树和回溯>lt.112. 路径总和

X.<tag-数组和二分查找>-lt.xx-xxxxxx + lt.xx-xxxxxx

lt.112. 路径总和 [案例需求]

[思路分析一, 递归]

[代码实现]
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {

        if(root == null)return false;
        return dfs(root, targetSum - root.val); /// !!!
    }
    //遍历二叉树的所有路径
    //遍历所有路径, 返回的是false
    public boolean dfs(TreeNode root, int count){
        
        //递归结束条件
        if(root.left == null && root.right == null && count == 0)return true;
        if(root.left == null && root.right == null  )return false;

        //单层递归逻辑
        //对左子树的处理:
        if(root.left != null){
            count -= root.left.val;
            if(dfs(root.left, count))return true;
            count += root.left.val;
        }

        //对右子树的处理
        if(root.right != null){
            count -= root.right.val;
            if(dfs(root.right, count))return true;
            count += root.right.val;
        }

        return false;
    }
}
[思路分析二, 迭代法]

[代码实现]
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        Queue nodes = new LinkedList<>();
        Queue nodesVal = new LinkedList<>();

        if(root == null)return false;

        nodes.add(root);
        nodesVal.add(root.val);

        while(!nodes.isEmpty()){
            root = nodes.poll();
            int temp = nodesVal.poll();

            if(root.left == null && root.right == null){
                if(temp == targetSum)return true;
                continue;
            }

            if(root.left != null){
                nodes.add(root.left);
                nodesVal.add(root.left.val + temp);
            }

            if(root.right != null){
                nodes.add(root.right);
                nodesVal.add(root.right.val + temp);
            }
        }

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

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

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