[Algorithms] Tree Data Structure in JavaScript

本文深入探讨了网页中常见的DOM树结构,通过JavaScript代码演示了如何从零开始构建一个DOM树,包括html、head、body等元素,并展示了树结构的打印结果。

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

*/

 

转载于:https://www.cnblogs.com/Answer1215/p/10134940.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值