Convert the department list to preorder traversal of the name of department tree
链接:https://www.nowcoder.com/questionTerminal/86dc86da50424b47b25ced3e9f97b056
来源:牛客网
输入
[[“d1”, “d0”, “IT”], [“d2”, “d0”, “RD”], [“d0”, “”, “The Company”], [“d3”, “d0”, “HR”]]
输出
[“The Company”,“HR”,“IT”,“RD”]
说明
On each level of the department tree, departments are listed in alphabetical order of the name
import java.util.*;
public class Solution {
/**
* Convert the department list to preorder traversal of the department tree
* @param departments string字符串二维数组 [["id1", "parentId", "name"]...], there's only one root department with empty parent id.
* @return string字符串一维数组
*/
LinkedList<String> res = new LinkedList<>();
public String[] listToTree (String[][] departments) {
// write code here
Map<String,Node> map = new HashMap<>();
int n = departments.length;
Node root=null;
for(int i=0;i<n;++i)
{
Node node = new Node(departments[i]);
map.put(node.id,node);
if (node.parentId==null || node.parentId.length()==0) {
root = node;
}
}
Arrays.sort(departments, (arr1, arr2) -> arr1[2].compareTo(arr2[2]));
for(String[] dep: departments) {
Node parent = map.get(dep[1]);
if(parent==null) continue;
Node self = map.get(dep[0]);
parent.sons.add(self);
}
dfs(map,root);
return res.toArray(new String[0]);
}
void dfs(Map<String,Node> map,Node root) {
if(root ==null) return;
res.add(root.name);
for(Node child: root.sons) {
dfs(map,child);
}
}
static class Node{
String id;
String parentId;
String name;
List<Node> sons = new LinkedList<>();
Node(String[] x) {
id = x[0];
parentId = x[1];
name = x[2];
}
}
}