关于leetcode:力扣-1519子树中标签相同的节点数

本题次要在于对树这种数据结构的考查,以及深度优先遍历的应用,优化时能够采取空间换工夫的策略。
<!– more –>

原题

给你一棵树(即,一个连通的无环无向图),这棵树由编号从 0  到 n – 1 的 n 个节点组成,且恰好有 n – 1 条 edges 。树的根节点为节点 0 ,树上的每一个节点都有一个标签,也就是字符串 labels 中的一个小写字符(编号为 i 的 节点的标签就是 labels[i] )

边数组 edges 以 edges[i] = [ai, bi] 的模式给出,该格局示意节点 ai 和 bi 之间存在一条边。

返回一个大小为 n 的数组,其中 ans[i] 示意第 i 个节点的子树中与节点 i 标签雷同的节点数。

树 T 中的子树是由 T 中的某个节点及其所有后辈节点组成的树。

示例 1:

输出:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"
输入:[2,1,1,1,1,1,1]
解释:节点 0 的标签为 'a' ,以 'a' 为根节点的子树中,节点 2 的标签也是 'a' ,因而答案为 2 。留神树中的每个节点都是这棵子树的一部分。
节点 1 的标签为 'b' ,节点 1 的子树蕴含节点 1、4 和 5,然而节点 4、5 的标签与节点 1 不同,故而答案为 1(即,该节点自身)。

示例 2:

输出:n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"
输入:[4,2,1,1]
解释:节点 2 的子树中只有节点 2 ,所以答案为 1 。
节点 3 的子树中只有节点 3 ,所以答案为 1 。
节点 1 的子树中蕴含节点 1 和 2 ,标签都是 'b' ,因而答案为 2 。
节点 0 的子树中蕴含节点 0、1、2 和 3,标签都是 'b',因而答案为 4 。

示例 3 :

输出:n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"
输入:[3,2,1,1,1]

示例 4:

输出:n = 6, edges = [[0,1],[0,2],[1,3],[3,4],[4,5]], labels = "cbabaa"
输入:[1,2,1,1,2,1]

示例 5:

输出:n = 7, edges = [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6]], labels = "aaabaaa"
输入:[6,5,4,1,3,2,1]
 ```

提醒:

* 1 <= n <= 10^5
* edges.length == n - 1
* edges[i].length == 2
* 0 <= ai, bi < n
* ai != bi
* labels.length == n
* labels 仅由小写英文字母组成

原题 url:https://leetcode-cn.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label

## 解题

### 首次尝试

这道题是要让咱们计算:在子树中,和以后节点字符雷同的节点个数。

那么咱们就必然须要构建树中各个节点的关系,那么就须要记录父子节点的关系,因为是一般的树,一个节点的子节点可能有多个,因而我用`LinkedList<Integer>[] tree`这样一个数组进行存储,其中`tree[i]`代表节点 i 的所有子节点。

至于求雷同节点的个数,我想着能够从根节点 0 开始一一遍历,先获取其第一层子节点,再依据第一层子节点一一获取,能够采纳广度优先遍历的模式。

让咱们看看代码:

class Solution {

public int[] countSubTrees(int n, int[][] edges, String labels) {
    // 结构树
    LinkedList<Integer>[] tree = new LinkedList[n];
    for (int[] edge : edges) {
        // edge[0]的子节点
        LinkedList<Integer> child = tree[edge[0]];
        if (child == null) {
            child = new LinkedList<>();
            tree[edge[0]] = child;
        }
        // 减少子节点
        child.add(edge[1]);
    }

    // 后果
    int[] result = new int[n];
    // 遍历并计算
    for (int i = 0; i < n; i++) {
        // 须要遍历的字符
        char cur = labels.charAt(i);
        // 该节点的子树中与该字符雷同的节点数
        int curCount = 0;
        // 广度优先遍历
        LinkedList<Integer> searchList = new LinkedList<>();
        searchList.add(i);
        while(!searchList.isEmpty()) {
            int index = searchList.removeFirst();
            if (cur == labels.charAt(index)) {
                curCount++;
            }
            // 找出该节点的子树
            if (tree[index] == null) {
                continue;
            }
            searchList.addAll(tree[index]);
        }

        result[i] = curCount;
    }

    return result;
}

}

提交之后,发现有`谬误`。谬误的状况是:

输出:
4
[[0,2],[0,3],[1,2]]
“aeed”

输入:
[1,2,1,1]

预期:
[1,1,2,1]


依据这样输出,我结构出的树是:

1 0
/ \
2 3


但依据预期后果反推出来的树是:
0

/ \
2 3
/
1


那么输出中最初给出的`[1,2]`就不是从`父节点`指向`子节点`,也就是输出中给出的边关联的节点程序,是任意的。

那咱们的树到底该如何结构呢?

### 双向记录结构树

既然咱们在结构树的时候,无奈间接得出父子关系,那么就将对应两个节点同时记录另一个节点。

依据题目中给出的条件:`树的根节点为节点 0`。这样咱们在遍历的时候,就从 0 开始,只有 0 关联的节点,肯定是 0 的子节点。将这些节点进行标记,这样再递归拜访接下来的节点时,如果是标记过的,则阐明是父节点,这样就能够明确父子节点关系了。

至于遍历的时候,因为这次咱们是不晓得父子节点关系的,所以无奈间接采纳广度优先遍历,换成`深度优先遍历`。

让咱们看看代码:

class Solution {

// 总节点数
int n;
// 树
Map<Integer, LinkedList<Integer>> tree;
// 字符串
String labels;
// 最终后果
int[] result;

public int[] countSubTrees(int n, int[][] edges, String labels) {
    this.n = n;
    this.labels = labels;
    result = new int[n];

    LinkedList<Integer> list;
    // 双向结构树的关系
    tree = new HashMap<>(n / 4 * 3 + 1);
    for (int[] edge : edges) {
        // 增加映射关系
        list = tree.computeIfAbsent(edge[0], k -> new LinkedList<>());
        list.add(edge[1]);
        list = tree.computeIfAbsent(edge[1], k -> new LinkedList<>());
        list.add(edge[0]);
    }

    
    // 深度优先搜寻
    dfs(0);

    return result;
}

public int[] dfs(int index) {
    // 以后子树中,所有字符的个数
    int[] charArray = new int[26];

    // 开始计算,标记该节点曾经计算过
    result[index] = 1;
    // 取得其关联的节点
    List<Integer> nodes = tree.get(index);
    // 遍历
    for (int node : nodes) {
        // 如果该节点曾经拜访过
        if (result[node] > 0) {
            continue;
        }

        // 递归遍历子节点
        int[] array = dfs(node);
        for (int i = 0; i < 26; i++) {
            charArray[i] += array[i];
        }
    }
    // 将以后节点的值计算一下
    charArray[labels.charAt(index) - 'a'] += 1;
    result[index] = charArray[labels.charAt(index) - 'a'];
    return charArray;
}

}

提交OK,执行用时`136ms`,超过`36.71%`,内存耗费`104.5MB`,超过`91.38%`。

工夫复杂度上,应该是要钻研`dfs`办法中的两个`for`循环,外层必定是每个节点都遍历一遍,内层还须要遍历`26`个英文字母,也就是`O(n)`。

空间复杂度上,最大的应该就是存储节点映射关系的`tree`了,外面实际上就是 2n 个节点(因为每条边对应的两个节点都会相互存一次对方),因而也就是`O(n)`。

尽管过了,但执行速度很慢,能够进一步优化。

### 用空间换工夫

针对我下面的解法,其中`tree`我是用的`Map`,尽管其`get`办法实践上是`O(n)`,但毕竟波及 hash,能够优化成数组。

至于每次取节点对应的字符所用的`charAt`办法,具体其实是:
public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}
每次都会查看一次 index,其实这齐全是能够省略的,因而能够提前结构好每个地位对应的值,也用一个数组存储。

让咱们看看新的代码:

class Solution {

// 总节点数
int n;
// 树
LinkedList<Integer>[] tree;
// 每个节点的值(用数字示意)
int[] nodeValueArray;
// 最终后果
int[] result;

public int[] countSubTrees(int n, int[][] edges, String labels) {
    this.n = n;
    nodeValueArray = new int[n];
    result = new int[n];

    // 双向结构树的关系
    tree = new LinkedList[n];
    for (int i = 0; i < n; i++) {
        tree[i] = new LinkedList<>();
    }
    for (int[] edge : edges) {
        // 增加映射关系
        tree[edge[0]].add(edge[1]);
        tree[edge[1]].add(edge[0]);
    }

    // 生成节点的值
    for (int i = 0; i < n; i++) {
        nodeValueArray[i] = labels.charAt(i) - 'a';
    }

    // 深度优先搜寻
    dfs(0);

    return result;
}

public int[] dfs(int index) {
    // 以后子树中,所有字符的个数
    int[] charArray = new int[26];

    // 开始计算,标记该节点曾经计算过
    result[index] = 1;
    // 取得其关联的节点
    List<Integer> nodes = tree[index];
    // 遍历
    for (int node : nodes) {
        // 如果该节点曾经拜访过
        if (result[node] > 0) {
            continue;
        }

        // 递归遍历子节点
        int[] array = dfs(node);
        for (int i = 0; i < 26; i++) {
            charArray[i] += array[i];
        }
    }
    // 将以后节点的值计算一下
    charArray[nodeValueArray[index]] += 1;
    result[index] = charArray[nodeValueArray[index]];
    return charArray;
}

}

提交之后,执行用时是`96ms`,内存耗费是`402.2MB`。看来优化的成果并不显著。

### 钻研一下目前最优解法

这个解法真的是奇妙,执行用时`20ms`,超过了`100%`,内存耗费`76.3MB`,超过了`100%`。

我在代码中减少了正文,不便大家了解。但这样的写法,钻研一下是可能看懂,但让我想预计是永远不可能想进去,能够让大家也一起学习和借鉴:

public class Solution {

static class Next {

Next next;
Node node;

Next(Next next, Node node) {
  this.next = next;
  this.node = node;
}

}

static class Node {

/**
 * 以后节点的index
 */
final int index;

/**
 * 以后节点对应的字符值(减去'a')
 */
final int ci;

/**
 * 所有关联的节点
 */
Next children;

/**
 * 该节点的父节点
 */
Node parent;

/**
 * 子树中和该节点含有雷同字符的节点总个数
 */
int result;

/**
 * 是否还在队列中,能够了解为是否已拜访过
 */
boolean inQueue;

public Node(int index, int ci) {
  this.index = index;
  this.ci = ci;
  this.result = 1;
}

/**
 * 从后往前,找到以后节点没有拜访过的第一个子节点
 */
Node popChild() {
  for (; ; ) {
    // 以后节点的所有关联节点
    Next n = this.children;
    // 如果没有,阐明子节点都遍历完了
    if (n == null) {
      return null;
    }
    // 从后往前移除关联节点
    this.children = n.next;
    // 返回第一个没有拜访过的节点
    if (!n.node.inQueue) {
      return n.node;
    }
  }
}

/**
 * 拜访了该节点
 */
Node enqueue(Node[] cnodes) {
  // 该节点标记为拜访过
  this.inQueue = true;
  // 记录该节点的父节点
  this.parent = cnodes[ci];
  // 那么当初该字符值对应的最高节点,就是以后节点。
  // 这样如果之后也遇到雷同字符的子节点,就能够为子节点赋值其父节点,也就是下面一行是无效的
  cnodes[ci] = this;
  return this;
}

/**
 * 退出该节点
 */
void dequeue(Node[] cnodes, int[] res) {
  // 之后会拜访该节点的兄弟节点,因而父节点须要从新设置
  cnodes[ci] = this.parent;
  // 设置以后节点的值
  res[index] = this.result;
  // 父节点也能够进行累加
  if (this.parent != null) {
    this.parent.result += this.result;
  }
}

void link(Node x) {
  // this节点和x节点,相互绑定
  this.children = new Next(this.children, x);
  x.children = new Next(x.children, this);
}

}

public int[] countSubTrees(int n, int[][] edges, String labels) {

// 结构树
Node[] nodes = new Node[n];
// 每个节点对应的字符
for (int i = 0; i < n; i++) {
  nodes[i] = new Node(i, labels.charAt(i) - 'a');
}
// 通过边的关系,将节点相互绑定
for (int[] es : edges) {
  nodes[es[0]].link(nodes[es[1]]);
}

// 最终的后果
int[] res = new int[n];
// 以后拜访的节点下标
int sz = 0;
// 26个小写英文字母对应的节点数组
Node[] cnodes = new Node[26];
// 上面三行能够合并成这一行:
// Node node = nodes[sz++] = nodes[0].enqueue(cnodes);
nodes[sz] = nodes[0].enqueue(cnodes);
// 以后拜访的节点
Node node = nodes[sz];
// 因为以后节点曾经拜访过,天然下标须要+1
sz++;

for (; ; ) {
  // 从后往前,找到以后节点没有拜访过的第一个子节点
  Node child = node.popChild();
  // 如果曾经全副拜访过了
  if (child == null) {
    // 开始计算
    node.dequeue(cnodes, res);
    if (--sz == 0) {
      break;
    }
    // 回溯到父节点
    node = nodes[sz - 1];
  } else {
    // 保障了相邻节点肯定是父子节点
    node = nodes[sz++] = child.enqueue(cnodes);
  }
}
return res;

}
}


## 总结
   
以上就是这道题目我的解答过程了,不晓得大家是否了解了。本题次要在于对树这种数据结构的考查,以及深度优先遍历的应用,优化时能够采取空间换工夫的策略。

有趣味的话能够拜访我的博客或者关注我的公众号、头条号,说不定会有意外的惊喜。

[https://death00.github.io/](https://death00.github.io/)

公众号:健程之道

![](https://static01.imgkr.com/temp/dcfad764025e4ea9ab8d73ef0934efdd.png)

![](https://static01.imgkr.com/temp/003e8c4d5f5544b0bd70dfe7aa63bf60.png)





评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理