算法打卡:第9周

问题一

剑指Offer 34.二叉树中和为某一值的路径:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/

思路:递归遍历并保存所有路径,然后计算符合要求的路径。

public List<List<Integer>> pathSum(TreeNode root, int target) {
    if (root == null) {
        return new ArrayList<>();
    }
    List<List<Integer>> list = this.recursion(root);
    Iterator<List<Integer>> it = list.iterator();
    while (it.hasNext()) {
        List<Integer> path = it.next();
        int sum = path.stream().mapToInt(Integer::intValue).sum();
        if (sum != target) {
            it.remove();
        } else {
            Collections.reverse(path);
        }
    }
    return list;
}

public List<List<Integer>> recursion(TreeNode root) {
    List<List<Integer>> list = new ArrayList<>();
    if (root.left == null && root.right == null) {
        List<Integer> path = new ArrayList<>();
        list.add(path);
    } else {
        if (root.left != null) {
            list.addAll(this.recursion(root.left));
        }
        if (root.right != null) {
            list.addAll(this.recursion(root.right));
        }
    }
    for (List<Integer> path : list) {
        path.add(root.val);
    }
    return list;
}

问题二

特定深度节点链表:https://leetcode-cn.com/problems/list-of-depth-lcci/

思路:递归遍历,使用map保存所有层的节点信息。然后转化为ListNode

public ListNode[] listOfDepth(TreeNode tree) {
    if (tree == null) {
        return new ListNode[0];
    }
    Map<Integer, List<Integer>> map = new HashMap<>();
    this.recursion(map, tree, 1);
    ListNode[] listNode = new ListNode[map.size()];
    for (int i = 1; i <= map.size(); i++) {
        List<Integer> list = map.get(i);
        if (list == null) {
            break;
        }
        ListNode root = new ListNode(-1);
        ListNode curr = root;
        for (Integer node : list) {
            curr.next = new ListNode(node);
            curr = curr.next;
        }
        listNode[i - 1] = root.next;
    }
    return listNode;
}

public void recursion(Map<Integer, List<Integer>> map, TreeNode root, int depth) {
    List<Integer> list = map.get(depth);
    if (list == null) {
        list = new ArrayList<>();
        map.put(depth, list);
    }
    list.add(root.val);
    depth++;
    if (root.left != null) {
        this.recursion(map, root.left, depth);
    }
    if (root.right != null) {
        this.recursion(map, root.right, depth);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值