[Algorithms] Tree Data Structure in JavaScript
JavaScript in Data Tree Structure Algorithms
2023-09-14 08:59:16 时间
In a tree, nodes have a single parent node and may have many children nodes. They never have more than one parent nor point to any siblings.
The most common tree structure you see is a web page. The underlying structure is often called the "DOM tree". The html
element forms the root of our tree, with children of head
and body
, so on and so forth. In this lesson, we'll create a quick example of a DOM tree with our tree data structure.
function crateNode (key) { let children = []; return { key, children, addChild (cKey) { const childNode = crateNode(cKey) this.children.push(childNode) return childNode; } } } function createTree (rootKey) { const root = crateNode(rootKey); function print () { let result = ''; function traverse (node, visitFn, depth) { visitFn(node, depth); if (node.children.length) { node.children.forEach(n => traverse(n, visitFn, depth + 1)) } } function addKeyToResult(node, depth) { result += result.length === 0 ? node.key : `\n${' '.repeat(depth * 2)}${node.key}` } traverse(root, addKeyToResult, 0) return result; } return { root, print } } const dom = createTree('html') const head = dom.root.addChild('head') const body = dom.root.addChild('body') const title = head.addChild('title - egghead Tree Lesson') const header = body.addChild('header') const main = body.addChild('main') const footer = body.addChild('footer') const h1 = header.addChild('h1 - Tree Lesson') const p = main.addChild('p - Learn about trees!') const copyright = footer.addChild(`Copyright ${new Date().getFullYear()}`) console.log(dom.print()) /* html head title - egghead Tree Lesson body header h1 - Tree Lesson main p - Learn about trees! footer Copyright 2018 */
相关文章
- javascript系列学习笔记-this
- 盘点那些非常实用的JavaScript测试框架
- JavaScript 第四天
- 查询Oracle中执行多列IN查询的技巧(oracle多列in)
- 和in的区别深入研究MySQL查询条件中的=与IN的区别(mysql查询条件中)
- 查询优化Oracle中IN查询的技巧(oracle优化in)
- 查询MySQL中的IN字符串查询详解(mysql字符串in)
- 查询MySQL中使用IN语句实现多字段查询(mysql多字段in)
- MySQL中利用IN查询实现多参数搜索(mysql的in查询)
- MySQL中使用IN操作符的查询效率分析(mysql中in的效率)
- MySQL中IN操作存在漏洞(mysql中in有漏)
- MYSQL中IN关键字如何高效处理大量数据(mysql中in关键字)
- 探索Oracle中IN查询的精彩之处(oracle中的in查询)
- 从Oracle到NO IN数据库迁移指南(oracle no in)
- 用JavaScript事件串连执行多个处理过程的方法
- JavaScript进阶教程(第三课)
- javascript实现轮显新闻标题链接
- javascript在一段文字中的光标处插入其他文字
- javascript静态树菜单实现代码
- Javascript世界时区时间显示代码
- javascript学习笔记(十)js对象继承
- 使用JavaScript实现对象匀速/变速运动的方法
- javascript实现信息的显示和隐藏如注册页面
- javascript简单实现图片预加载
- JavaScript实现的双向跨域插件分享
- Javascript保存网页为图片借助于html2canvas库实现