Forgot password?
 Create new account
View 119|Reply 0

树的图示

[Copy link]

3146

Threads

8493

Posts

610K

Credits

Credits
66158
QQ

Show all posts

hbghlyj Posted at 2023-7-19 02:35:02 |Read mode
是一种数据结构。输入树,用Javascript输出显示层次关系的字符串
  1. class TreeNode {
  2.   constructor(value) {
  3.     this.value = value;
  4.     this.children = [];
  5.   }
  6.   addChild(child) {
  7.     this.children.push(child);
  8.   }
  9. }
  10. function convertTreeToDiagram(node, prefix = '', isLast = true) {
  11.   let diagram = prefix;
  12.   if (isLast) {
  13.     diagram += 'o-';
  14.     prefix += '  ';
  15.   } else {
  16.     diagram += 'o-';
  17.     prefix += '| ';
  18.   }
  19.   diagram += node.value + '\n';
  20.   const childCount = node.children.length;
  21.   for (let i = 0; i < childCount; i++) {
  22.     const child = node.children[i];
  23.     const isLastChild = i === childCount - 1;
  24.     diagram += convertTreeToDiagram(child, prefix, isLastChild);
  25.   }
  26.   return diagram;
  27. }
Copy the Code

用例
  1. const tree = new TreeNode('A');
  2. const childB = new TreeNode('B');
  3. const childC = new TreeNode('C');
  4. const childD = new TreeNode('D');
  5. childB.addChild(new TreeNode('E'));
  6. childB.addChild(new TreeNode('F'));
  7. childD.addChild(new TreeNode('G'));
  8. tree.addChild(childB);
  9. tree.addChild(childC);
  10. tree.addChild(childD);
  11. const diagram = convertTreeToDiagram(tree);
  12. console.log(diagram);
Copy the Code

o-A
  o-B
  | o-E
  | o-F
  o-C
  o-D
    o-G

文件系统:
The-directory-tree-that-we-are-going-to-visualize-with-our-tool-as-visualized-by.png

手机版Mobile version|Leisure Math Forum

2025-4-20 22:13 GMT+8

Powered by Discuz!

× Quick Reply To Top Return to the list