zoukankan      html  css  js  c++  java
  • [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
                    : `
    ${' '.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
    
    */
  • 相关阅读:
    后CIO人如何规划职业生涯
    数据库设计三大范式应用实例剖析
    一个女孩从软件测试工程师到主管的成长
    一本适合测试初学者阅读的中文译著
    再看微软团队文化
    阳光的测试工作历程(转载)
    hdu 2795
    hdu 2426
    hdu 2255+hdu 3395
    hdu 3729
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10134940.html
Copyright © 2011-2022 走看看