【LeetCode】113.路径总和 II


1 问题

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

叶子节点是指没有子节点的节点。

示例 1

示例1

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]

示例 2

示例2

输入:root = [1,2,3], targetSum = 5
输出:[]

示例 3

输入:root = [1,2], targetSum = 0
输出:[]

提示

  • 树中节点总数在范围 [0, 5000] 内
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

2 解题思路

这一题是第 112 题第 257 题的组合增强版。
两种方法都是递归思想,常用的回溯法也是递归的一种,这题采用回溯法公式,可以马上解出来。公式参见【LeetCode】46.全排列

3 代码

/**
 * 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 {
    List<List<Integer>> res = new LinkedList();

    /**
     backtracking
     */
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (null == root) {
            return res;
        }
        LinkedList<Integer> track = new LinkedList();
        track.add(root.val);
        pathSum(root, targetSum, track);
        return res;
    }

    private void pathSum(TreeNode root, int targetSum, LinkedList<Integer> track) {
        if (null == root) {
            return;
        }
        //reach the leaf
        if (null == root.left && null == root.right && targetSum - root.val == 0) {
            res.add(new LinkedList(track));
            return;
        }
        if (null != root.left) {
            track.add(root.left.val);
            pathSum(root.left, targetSum - root.val, track);
            track.removeLast();
        }
        if (null != root.right) {
            track.add(root.right.val);
            pathSum(root.right, targetSum - root.val, track);
            track.removeLast();
        }
    }

    /**
     recursive
     */
    public List<List<Integer>> pathSum2(TreeNode root, int targetSum) {
        if (null == root) {
            return res;
        }
        LinkedList<Integer> track = new LinkedList();
        pathSum2(root, targetSum, track);
        return res;
    }

    private void pathSum2(TreeNode root, int targetSum, LinkedList<Integer> track) {
        if (null == root) {
            return;
        }
        track.add(root.val);
        if (null == root.left && null == root.right) {
            if (targetSum - root.val == 0) {
                res.add(new LinkedList(track));
            }
            return;
        }
        //注意track要采用新的链表
        pathSum2(root.left, targetSum - root.val, new LinkedList(track));
        pathSum2(root.right, targetSum - root.val, new LinkedList(track));
    }
}

文章作者: Kezade
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Kezade !
评论
  目录