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]
]

要求找出所有从根到叶子的节点之和为sum的路径。感觉跟前一题有点像,但是这道题要求找出所有可能的情况并返回,于是就想到了类似于回溯的方法。但是在写回溯的add/remove的时候还是卡住了,知道要在遇到叶子的val == sum的时候加入result集,但是不知道怎么普通的加加减减。如果遇到一个非叶子节点,需要check它有没有左右子树,如果有的话就要沿着这边继续遍历,没有其中一边的话其实啥也不用干(这里没有完全理解透)。继续遍历结束以后要把它给remove掉。

Runtime: 1 ms, faster than 100.00% of Java online submissions for Path Sum II.

Memory Usage: 38.8 MB, less than 5.03% of Java online submissions for Path Sum II.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<>();
        recursion(root, sum, result, new ArrayList<>());
        return result;
    }
    
    private void recursion(TreeNode root, int sum, List<List<Integer>> result, List<Integer> temp) {
        if (root == null) {
            return;
        }
        temp.add(root.val);
        if (root.val == sum && root.left == null && root.right == null) {
            result.add(new ArrayList<>(temp));
            return;
        }
        if (root.left != null) {
            recursion(root.left, sum - root.val, result, temp);
            temp.remove(temp.size() - 1);
        }
        if (root.right != null) {
            recursion(root.right, sum - root.val, result, temp);
            temp.remove(temp.size() - 1);
        }
    }
}

其他方法暂时放弃。

 

2020.10.21 二刷

磕磕绊绊差一点就写出来了,最后的remove的地方刚开始还是没搞对,直接递归完就remove了一次,结果发现给的test case结果多了个节点,看了下笔记感觉好像想通了。实际上是每次add完都要及时remove掉,如果单边有子节点,那在递归函数中就会把它加到temp里,等这次递归完了还需要把它remove掉,那就只能在调用它之后remove。如果单边没有子节点,那递归的时候直接return了并没有加它,所以就不用remove掉。代码跟上次一样就不po了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值