1519. Number of Nodes in the Sub-Tree With the Same Label

1 篇文章 0 订阅

Lc-1519
categories: [LeetCode]
tags: [DFS, BFS, medium]

1519. Number of Nodes in the Sub-Tree With the Same Label

题目大意:

给定一个被标记为从0 到n-1的n个节点的树(一个连通,无向无循环的图),根节点为0结点, 
并且每个结点也被标记了小写字母,所有的结点的小写字母按照结点顺序保存在一个字符串中labels,
第i个node的字母为labels[i], 同时给定一个二维数组edges,edges中连个结点表示这两个结点相连
返回一个大小为n的数组array,array[i] 表示第i个节点有相同小写字母label的所有子树中的节点的个数
注意:当前节点的子树也包括当前结点的树

解题思路:

首先这道题是一个典型的dfs,我们先用Map<Integer, List<Integer>> 去记录
每个点所相连接的其他点,并将它们保存在for loop中,在for loop中,记住我们要将
每队相连的结点要彼此保存在对方的List当中
初始化一个boolean数组去记录每个结点是否遍历过
然后开始dfs搜索,最后将答案保存在ans数组中并返回。

在dfs中,我们将当前遍历的点在visted中标记为true
然后初始化一个26长度的数组currCounts代表26个字母,
并在数组当前结点的label字母上+1,然后取出当前节点所相连其他结点的list
对list进行循环,在循环中,如果发现当前结点在visited中位false,说明
该节点还没有被查找过, 则对该节点进行dfs recursion
接下来循环26个字母, 将子节点label的字母个数分别加到当前的currCounts
最后将currCounts数组中找到与当前结点label相同的字母个数都传递给ans[i]
i 为当前结点对应的下标在ans中,最后返回currCounts[]数组

注意:

None

复杂度:

Time Complexity: O(NC) N is the number of nodes on tree and C is the length of characters which is 26
Space Complexity: O(NC)

Code示例:

class Solution {
    public int[] countSubTrees(int n, int[][] edges, String labels) {
        Map<Integer, List<Integer>> map = new HashMap<>();
        
        for (int[] edge : edges) {
            int node0 = edge[0], node1 = edge[1];
            List<Integer> list0 = map.getOrDefault(node0, new ArrayList<>());
            List<Integer> list1 = map.getOrDefault(node1, new ArrayList<>());
            list0.add(node1);
            list1.add(node0);
            map.put(node0, list0);
            map.put(node1, list1);
        }
        
        int[] ans = new int[n];
        boolean[] visited = new boolean[n];
        dfs(0, ans, visited, map, labels);
        return ans;
    }
    
    public int[] dfs(int node, int[] ans, boolean[] visited, Map<Integer, List<Integer>> map, String labels) {
        visited[node] = true;
        int[] currCounts = new int[26];
        currCounts[labels.charAt(node) - 'a']++;
        List<Integer> list = map.get(node);
        for (int next : list) {
            if (!visited[next]) {
                int[] child = dfs(next, ans, visited, map, labels);
                for (int i = 0; i < 26; i++) {
                   currCounts[i] += child[i]; 
                }
            }
        }
        
        ans[node] = currCounts[labels.charAt(node) - 'a'];
        return currCounts;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值