leetcode 113. 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]
]

给出一个二叉树,让返回所有root-to-leaf 路径,满足路径上节点值的和=sum
注意是root to leaf 路径,中间即使和=sum,如果不到leaf节点,也不算满足

思路:
因为要找出所有路径,所以用DFS遍历所有路径
判断和=sum时一定要判断是不是leaf节点

另外注意DFS中一个节点遍历完后从path中remove掉时,要直接remove掉最后一个即可,不能按值remove,比如path.remove(new Integer(1))
如果按值remove,会有一个后果,比如path中存了[1,2,1], 本意是remove最后一个1,然而按值remove的话会把第一个1 remove掉,路径讲究顺序,顺序不同也是会WA的

//1ms, 100%(current time)
    private int addSum = 0;
    
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> path = new ArrayList<Integer>();
               
        dfs(root, path, sum, result);
        
        return result;
    }
    
    public void dfs(TreeNode root, List<Integer> path, int sum, List<List<Integer>> result) {
        if (root == null) {
            return;
        }
        
        addSum += root.val;                  
        
        path.add(root.val);
        
        if (addSum == sum && root.left == null && root.right == null) {           
            List<Integer> tmpPath = new ArrayList<Integer>(path);
            result.add(tmpPath);
            addSum -= root.val;
            path.remove(path.size() - 1);
            return;
        }
        
        dfs(root.left, path, sum, result);
        
        dfs(root.right, path, sum, result);
        addSum -= root.val;
        path.remove(path.size() - 1);
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值