[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
*/
[Algorithms] Tree Data Structure in JavaScript的更多相关文章
- Python:  tree data structure
		
# 树结构 from pythonds.basic.stack import Stack #pip install pythonds from pythonds.trees.binaryTree im ...
 - 树状结构  Tree data structure in C#
		
delegate void TreeVisitor<T>(T nodeData); class NTree<T> { private T data; private Linke ...
 - [Algorithm] Linked List Data Structure in JavaScript
		
A linked list is a collection of items where each item points to the next one in the list. Because o ...
 - [Algorithom] Stack Data Structure in JavaScript
		
A stack is a collection of items that obeys the principle of "last in, first out". Like a ...
 - CDOJ 483 Data Structure Problem DFS
		
Data Structure Problem Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/proble ...
 - 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design
		
字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...
 - LeetCode208 Implement Trie (Prefix Tree). LeetCode211 Add and Search Word - Data structure design
		
字典树(Trie树相关) 208. Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith ...
 - [Algorithm] JavaScript Graph Data Structure
		
A graph is a data structure comprised of a set of nodes, also known as vertices, and a set of edges. ...
 - [Algorithm] Heap data structure and heap sort algorithm
		
Source, git Heap is a data structure that can fundamentally change the performance of fairly common ...
 
随机推荐
- HTML5之中国象棋,附带源码!
			
好久没写随笔了,好怀恋2013年的日子,因为现在不能回到过去了! 再见了 感谢你为我做的一切! 进入正题:HTML5之中国象棋 很小就会下象棋了, 这是象棋的测试地址:点击我吧 然后点击里面的象 ...
 - python - 数据驱动测试 - ddt
			
# -*- coding:utf-8 -*- ''' @project: jiaxy @author: Jimmy @file: study_ddt.py @ide: PyCharm Communit ...
 - python补漏----isinstance 和 issubclass
			
一.isinstance Python 中的isinstance函数 isinstance是Python中的一个内建函数 语法: isinstance(object, classinfo) 如果参数o ...
 - 使用mysql监视器即命令行下的mysql
			
命令行下登录mysql 首先必须在alias下有设置mysql, 我的mysql安装的位置在/usr/local/mysql 于是做了一个别名: alias mysql='/usr/local/mys ...
 - JavaScript 专题系列第六篇,讲解深浅拷贝的技巧和以及实现深浅拷贝的思路
			
拷贝也是面试经典呐! 数组的浅拷贝 如果是数组,我们可以利用数组的一些方法比如:slice.concat 返回一个新数组的特性来实现拷贝. 比如: var arr = ['old', 1, tru ...
 - Python守护进程、进程互斥锁、进程间通信ICP(Queue队列)、生产者消费者模型
			
知识点一:守护进程 守护进程:p1.daemon=True 守护进程其实就是一个“子进程“,守护=>伴随 守护进程会伴随主进程的代码运行完毕后而死掉 进程:当父进程需要将一个任务并发出去执行,需 ...
 - ASP.NET配置设置-关于web.config各节点的讲解
			
在msdn中搜索:“ASP.NET配置设置”,可以查看各个节点的配置. httpRuntime 元素:配置 ASP.NET HTTP 运行时设置,以确定如何处理对 ASP.NET 应用程序的请求.
 - 【bzoj3252】攻略  贪心+DFS序+线段树
			
题目描述 题目简述:树版[k取方格数] 众所周知,桂木桂马是攻略之神,开启攻略之神模式后,他可以同时攻略k部游戏. 今天他得到了一款新游戏<XX半岛>,这款游戏有n个场景(scene),某 ...
 - Angular JS知识小总结
			
1.什么是Angular JS? AngularJS 是一个为动态WEB应用设计的 JavaScript结构框架. 2.Angular JS的用处? --它是为了克服HTML在构建应用上的不足而设计 ...
 - BZOJ2298 [HAOI2011]problem a  【dp】
			
题目 一次考试共有n个人参加,第i个人说:"有ai个人分数比我高,bi个人分数比我低."问最少有几个人没有说真话(可能有相同的分数) 输入格式 第一行一个整数n,接下来n行每行两个 ...