113. Path Sum II

本文详细解析了LeetCode上的Path Sum II题目,通过深度优先遍历算法寻找二叉树中所有根到叶子节点路径,使得路径上节点值之和等于给定的数值。示例展示了如何使用递归实现这一过程。

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,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

 

来自 <https://leetcode.com/problems/path-sum-ii/>

 

 

题解:Path Sum题的变形,给出一个二叉树和一个值,求出所有路径上节点值得和与之相等的路径,并打印出所有路径。同样是路径遍历的问题,也可以考虑使用深度优先遍历的方法。我们看一下递归过程:

递归结束条件:当前节点为叶节点,也就是左右子树都为null时,终止递归,此时如果传递的sum值是0,就可以将当前递归过程的path加入到路径列表中,否则,就不需要加入。在终止递归前,需要将当前叶节点的值从path中移除,以便下一条路径的递归。

递归函数:分别对左右子树执行递归函数,完成后从path中删除当前节点。

 

public class PathSumII {

        public List<List<Integer>> pathSum(TreeNode root, int sum) {

                List<List<Integer>> paths = new ArrayList<>();

                List<Integer> path = new ArrayList<>();

                dfs(root, sum, paths, path);

                return paths;

        }



        private void dfs(TreeNode root, int sum, List<List<Integer>> paths, List<Integer> path){

                if(root == null)

                        return;

                path.add(root.val);

                if(root.left == null && root.right == null){

                        if(path.size() > 0 && sum-root.val == 0){

                                List<Integer> temp = new ArrayList<>();

                                path.forEach(x -> temp.add(x));

                                paths.add(temp);

                        }

                        path.remove(path.size()-1);

                        return;

                }

//        if(root == null && sum != 0){

//            if(path.size() > 0){

//                path.remove(path.size()-1);

//            }

//            return;

//        }

                dfs(root.left, sum-root.val, paths, path);

                dfs(root.right, sum-root.val, paths, path);

                path.remove(path.size()-1);

                return;

        }

        

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值