113. Path Sum II

本文介绍了一种解决二叉树路径求和问题的方法,通过递归深度优先搜索(DFS),寻找所有从根节点到叶子节点的路径,使得路径上节点值的总和等于给定的目标值。

题目描述

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

给定二叉树和求和,找到所有根到叶路径,其中每个路径的总和等于给定的总和。

Note: A leaf is a node with no children.

注意:叶子是没有子节点的节点。

Example:

Given the below binary tree and sum = 22,

思路与实现

递归(DFS)

class Solution {
    private List<List<Integer>> res = new ArrayList<>();
    private List<Integer> mid = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if (root == null)
            return res;
        dfs(root, 0, sum);
        
        return res;
    }

    private void dfs(TreeNode node, int sum, int target) {
        mid.add(node.val);
        
        if (node.left == null && node.right == null) {
            if (sum + node.val == target) 
                res.add(new ArrayList<>(mid));
        } else {
            if (node.left != null) 
                dfs(node.left, sum+node.val, target);
            
            if (node.right != null)
                dfs(node.right, sum+node.val, target);
        }
        
        mid.remove(mid.size()-1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值