noaman_wgs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
//输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。 
//
//
//
// 示例:
//给定如下二叉树,以及目标和 target = 22,
//
//
// 5
// / \
// 4 8
// / / \
// 11 13 4
// / \ / \
// 7 2 5 1
//
//
// 返回:
//
//
//[
// [5,4,11,2],
// [5,8,4,5]
//]
//
//
//
//
// 提示:
//
//
// 节点总数 <= 10000
//
//
// 注意:本题与主站 113 题相同:https://leetcode-cn.com/problems/path-sum-ii/
// Related Topics 树 深度优先搜索
// 👍 145 👎 0

class Solution {

    private List<List<Integer>> pathList = new ArrayList<>();
    private int sum = 0;
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        if (root == null) {
            return new ArrayList<>();
        }

        List<TreeNode> tmpList = new ArrayList<>();
        dfsTree(root, target, tmpList);
        return pathList;
    }

    private void dfsTree(TreeNode root, int target, List<TreeNode> tmpList) {
        if (root == null) {
            return;
        }

        // 必须遍历到最底层的子节点,才算一条路径结束。此时再判断整个路径之和是否等于目标值
        if (root.left == null && root.right == null) {
            if (sum + root.val == target) {
                copyValue(tmpList, root);
                return;
            }
        } else {
            // 不等于,则继续遍历
            tmpList.add(root);
        }
        // 此处容易错过
        sum += root.val;

        // 先遍历左子树
        dfsTree(root.left, target, tmpList);
        // 再遍历右子树
        dfsTree(root.right, target, tmpList);
        // 左右子树都遍历完,就移除当前节点,递归到父节点,并减去当前值
        tmpList.remove(root);
        sum -= root.val;
    }

    private void copyValue(List<TreeNode> tmpList, TreeNode root) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < tmpList.size(); i++) {
            list.add(tmpList.get(i).val);
        }
        list.add(root.val);
        pathList.add(list);
    }
}

 








posted on 2021-03-13 00:24  noaman_wgs  阅读(69)  评论(0编辑  收藏  举报