LeetCode13_二叉树路径和(DFS递归、BFS双队列)

一、题目描述

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

在这里插入图片描述

二、题解

2.1DFS递归

观察要求我们完成的函数,我们可以归纳出它的功能:询问是否存在从当前节点 root 到叶子路径 ,满足其路径为和 为 sum

可以先假定 从根节点开始向下遍历 左、右子节点的时候,将问题化小,假定根节点到当前节点的和 为 val

我们需要判断的是,当前节点(如以root.left 为根节点 )是否存在 sum - val 的叶子节点

  • 当然该节点的左右节点都是要进行递归的 —》hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val),对应着每个节点的两个节点
  • 直到递归的结束条件—》root.left == null && root.right == null 即到了一个叶子节点,
class Solution {
    
    
    public boolean hasPathSum(TreeNode root, int sum) {
    
    
        if (root == null) {
    
    
            return false;
        }
        if (root.left == null && root.right == null) {
    
    
            return sum == root.val;
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}


2.2BFS双队列

思路

广度搜索的方式,记录从根节点到当前节点的路径和

防止重复计算,我们可以使用两个队列,分别存储将要遍历的 节点 以及 根节点到 这些节点的路径和

每次 节点队列nodeQ 和 当前节点到根节点的值 valQ 是对应的,迭代碰到叶子节点就比较

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public boolean hasPathSum(TreeNode root, int sum) {
    
    
        if(root == null){
    
    
            return false;
        }
        //双队列
        Queue<TreeNode> nodeQ = new LinkedList<TreeNode>();
        Queue<Integer> valQ = new LinkedList<Integer>();

        //根节点进队
        nodeQ.offer(root);
        //根节点值进队
        valQ.offer(root.val);

        while(!nodeQ.isEmpty()){
    
    
            //一次取出一个节点
            TreeNode now = nodeQ.poll();
            //取出的一个节点的值
            int temp = valQ.poll();

            //一个叶子节点
            if(now.left == null && now.right == null){
    
    
                if(temp == sum){
    
    
                    return true;
                }
                else{
    
    
                    continue;
                }
            }
            //不是接着BFS 
            if(now.left != null){
    
    
                nodeQ.offer(now.left);
                valQ.offer(now.left.val + temp);
            }
            if(now.right != null){
    
    
                nodeQ.offer(now.right);
                valQ.offer(now.right.val + temp);
            }

        }
        return false;

    }
    
}

猜你喜欢

转载自blog.csdn.net/qq_24654501/article/details/111303147