Leetcode 112. 路径总和

本文详细解析了LeetCode题目112路径总和的两种解法,包括递归解法和深度优先搜索结合前序遍历的非递归解法,提供了清晰的代码实现,帮助读者理解如何判断二叉树中是否存在从根节点到叶子节点的路径,其路径上的节点值之和等于给定的目标值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

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

在这里插入图片描述
来自力扣:leetcode 112. 路径总和

解答

解法一:递归

按照前序遍历的顺序递归。

当到达叶子结点的时候,判断此时 sum 是否能被减成 0。

代码
/**
 * 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;
        if(root.left == null && root.right == null) return sum == root.val;
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}
结果

在这里插入图片描述

解法二:深度搜索+前序遍历

其实就是模拟前序遍历的非递归版。

使用 数据结构,注意 先压右结点,后压左结点 即可。

代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Solution {
    
    class Pair {
        TreeNode node;
        int need;
        
        Pair(TreeNode node, int need) {
            this.node = node;
            this.need = need;
        }
    }
    
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) return false;
        
        LinkedList<Pair> stack = new LinkedList<>();         
        stack.push(new Pair(root, sum));
        while(!stack.isEmpty()) {
            Pair pair = stack.pop();
            TreeNode node = pair.node;
            int need = pair.need;
            
            if(node.left == null && node.right == null && need == node.val) {
                return true;
            }
            
            if(node.right != null) {
                stack.push(new Pair(node.right, need - node.val));
            }
            
            if(node.left != null) {
                stack.push(new Pair(node.left, need - node.val));
            }
        }
        
        return false;
    }
}
结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值