[Algorithms] Tree Data Structure in JavaScript

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

*/
复制代码

 

posted @   Zhentiw  阅读(257)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-12-18 [Python] Indexing An Array With Another Array with numpy
2017-12-18 [Python] Accessing Array Elements
2017-12-18 [Python] ndArray of numpy
2017-12-18 [React] Implement a Higher Order Component with Render Props
2017-12-18 [React] Implement a React Context Provider
2016-12-18 [React Native] Animate Styles of a React Native View with Animated.timing
2016-12-18 [Compose] 10. Capture Side Effects in a Task
点击右上角即可分享
微信分享提示