zoukankan      html  css  js  c++  java
  • [LeetCode] 113. 路径总和 II

    题目链接 : https://leetcode-cn.com/problems/path-sum-ii/

    题目描述:

    给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

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

    示例:

    给定如下二叉树,以及目标和 sum = 22,

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

    返回:

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

    思路:

    和上一题一样, 用DFS只不过在遍历时候,要记录val而已

    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
            res = []
            if not root: return []
            def helper(root,sum, tmp):
                if not root:
                    return 
                if not root.left and not root.right and sum - root.val == 0 :
                    tmp += [root.val]
                    res.append(tmp)
                    return 
                helper(root.left, sum - root.val, tmp + [root.val])
                helper(root.right, sum - root.val, tmp + [root.val])
            helper(root, sum, [])
            return res
    

    java

    class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> res = new ArrayList<>();
            helper(root, sum, res, new ArrayList<Integer>());
            return res;
        }
    
        private void helper(TreeNode root, int sum, List<List<Integer>> res, ArrayList<Integer> tmp) {
            if (root == null) return;
            tmp.add(root.val);
            if (root.left == null && root.right == null && sum - root.val == 0) res.add(new ArrayList<>(tmp));
            helper(root.left, sum - root.val, res, tmp);
            helper(root.right, sum - root.val, res, tmp);
            tmp.remove(tmp.size() - 1);
        }
    }
    

    相关题型 : 112. 路径总和

  • 相关阅读:
    CF-478C
    HDU-2074-叠筐
    HDU-2037-今年暑假不AC
    POJ-2785-4 Values whose Sum is 0
    HDU-1160-FatMouse's Speed
    HDU-1297-Children’s Queue
    Redis客户端管理工具的安装及使用
    Redis客户端管理工具,状态监控工具
    memcached可视化客户端工具
    javascript回调函数
  • 原文地址:https://www.cnblogs.com/powercai/p/11107476.html
Copyright © 2011-2022 走看看