【LeetCode-简单题】513. 找树左下角的值

题目

在这里插入图片描述

方法一:DFS递归 前序遍历

递归三部曲

  • 确定递归函数参数和返回值
  • 确定递归结束条件
  • 编写常规递归体

在这里插入图片描述
本题只会在叶子结点才会去统计结果 也就是 root.left==null&&root.right ==null
如果root.left或者 root.right 一方为null 都不需要往下递归 不关心非叶子结点

class Solution {
    boolean istrue = false;
    int targetSum = 0;
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null) return false;
        this.targetSum = targetSum;
        dfs(root,0);
        return istrue;
    }
    public void dfs(TreeNode root,int value){
        if(root.left==null&&root.right==null){//递归走到了叶子结点  可以对比了
                if(value+root.val == targetSum)
                istrue = true;
                return;
        }
        if(root.left != null)dfs(root.left,value+root.val);//不为空才往下递归
        if(root.right != null) dfs(root.right,value+root.val);
    }
}

方法二:BFS层序双队列

 public boolean hasPathSum(TreeNode root, int targetSum) {
         if (root == null) {
            return false;
        }
        Queue<TreeNode> queNode = new LinkedList<TreeNode>();
        Queue<Integer> queVal = new LinkedList<Integer>();
        queNode.offer(root);//记录节点
        queVal.offer(root.val);//记录路径和
        while (!queNode.isEmpty()) {
            root = queNode.poll();
            int val = queVal.poll();
            if(root.left==null&&root.right==null&&targetSum == val) return true;
            //每往节点队列加入节点  就往路径和队列加上对应的val值
            if(root.left!=null){
                queNode.offer(root.left);
                queVal.offer(val+root.left.val);
            }
            if(root.right!=null){
                queNode.offer(root.right);
                queVal.offer(val+root.right.val);
            }
        }
        return false;
    }

使用两个队列,分别记录节点的出入,和路径值的累加出入,每当走到了叶子结点再去判断结果
参考讲解链接:路径总和

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值