题目
- 根据所给字符串,按照分隔后的path构造前缀树,有就往下,没有就添加,前缀树
- 建立好前缀树后,深度优先遍历,根据当前层数打印时添加空格
class Node {
constructor(name) {
this.name = name;
this.next = [];
}
}
function process(arr) {
const node = new Node();
// 构造前缀树
for (let i = 0; i < arr.length; i++) {
const strArr = arr[i].split("\\");
const current = node;
for (let j = 0; j < strArr.length; j++) {
// 如果没有添加
if (!current.next.find((item) => item.name === strArr[i])) {
current.next.push(new Node(strArr[i]));
}
// 如果有往下
current = current.next.find((item) => item.name === strArr[i]);
}
}
// 深度优先遍历根据层级打印节点
print(node, 0);
function print(node, level) {
if (level !== 0) {
console.log(
Array.from({ length: level }, (_, index) => " ").join("") + node.name
);
}
for (let i = 0; i < node.next.length; i++) {
print(node.next[i], level + 1);
}
}
}