A binary tree is a tree where each node may only have up to two children. These children are stored on the leftand right properties of each node.

When traversing a binary tree, we have three common traversal algorithms: in order, pre-order, and post-order. In this lesson, we write each of these algorithms and explore their differences.

// Binary Trees and Tree Traversal

// Binary trees are trees whose nodes can only have up to two children

function createBinaryNode(key) {
return {
key,
left: null,
right: null,
addLeft(leftKey) {
const newLeft = createBinaryNode(leftKey)
this.left = newLeft
return newLeft
},
addRight(rightKey) {
const newRight = createBinaryNode(rightKey)
this.right = newRight
return newRight
}
}
} const TRAVERSALS = {
/**
* Javascript Call stack is Last in, First Out,
* So it keep calling
* TRAVERSALS.IN_ORDER(node.left, visitFn)
* Until it reach the bottom left node 'h' (b- d- h)
* h - visitFn get called
* h - TRAVERSALS.IN_ORDER(node.right, visitFn) get called
*
* d - visitFn get called
* d - left
* d - right
*
* b - visitFn
* b - left
* b - right
*/
IN_ORDER: (node, visitFn) => {
if (node !== null) {
console.log('left', node.left && node.left.key)
TRAVERSALS.IN_ORDER(node.left, visitFn)
console.log('call', node.key)
visitFn(node)
console.log('right', node.right && node.right.key)
TRAVERSALS.IN_ORDER(node.right, visitFn)
}
},
PRE_ORDER: (node, visitFn) => {
if (node !== null) {
visitFn(node)
TRAVERSALS.PRE_ORDER(node.left, visitFn)
TRAVERSALS.PRE_ORDER(node.right, visitFn)
}
},
POST_ORDER: (node, visitFn) => {
if (node !== null) {
TRAVERSALS.POST_ORDER(node.left, visitFn)
TRAVERSALS.POST_ORDER(node.right, visitFn)
visitFn(node)
}
}
} function createBinaryTree(rootKey) {
const root = createBinaryNode(rootKey) return {
root,
print(traversalType = 'IN_ORDER') {
let result = '' const visit = node => {
result += result.length === 0 ? node.key : ` => ${node.key}`
} TRAVERSALS[traversalType](this.root, visit) return result
}
}
} const tree = createBinaryTree('a')
const b = tree.root.addLeft('b')
const c = tree.root.addRight('c')
const d = b.addLeft('d')
const e = b.addRight('e')
const f = c.addLeft('f')
const g = c.addRight('g')
const h = d.addLeft('h')
const i = d.addRight('i') console.log('IN_ORDER: ', tree.print())// IN_ORDER: h => d => i => b => e => a => f => c => g
//console.log('PRE_ORDER: ', tree.print('PRE_ORDER')) // PRE_ORDER: a => b => d => h => i => e => c => f => g
  //console.log('POST_ORDER: ', tree.print('POST_ORDER')) // POST_ORDER: h => i => d => e => b => f => g => c => a
  exports.createBinaryNode = createBinaryNode
exports.createBinaryTree = createBinaryTree

Time complexity: O(n),

Space Complexity O(h) for average cases; h = logN -- this is because we need to stack all the function calls. worse cases: O(n)

[Algorithms] Build a Binary Tree in JavaScript and Several Traversal Algorithms的更多相关文章

  1. Construct Binary Tree from Inorder and Postorder Traversal

    Construct Binary Tree from Inorder and Postorder Traversal Given inorder and postorder traversal of ...

  2. Construct Binary Tree from Preorder and Inorder Traversal

    Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a ...

  3. (二叉树 递归) leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal

    Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume that ...

  4. (二叉树 递归) leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal

    Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that ...

  5. [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal 由先序和中序遍历建立二叉树

    Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume that ...

  6. 【LeetCode OJ】Construct Binary Tree from Preorder and Inorder Traversal

    Problem Link: https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-trave ...

  7. 36. Construct Binary Tree from Inorder and Postorder Traversal && Construct Binary Tree from Preorder and Inorder Traversal

    Construct Binary Tree from Inorder and Postorder Traversal OJ: https://oj.leetcode.com/problems/cons ...

  8. LeetCode:Construct Binary Tree from Inorder and Postorder Traversal,Construct Binary Tree from Preorder and Inorder Traversal

    LeetCode:Construct Binary Tree from Inorder and Postorder Traversal Given inorder and postorder trav ...

  9. 【题解二连发】Construct Binary Tree from Inorder and Postorder Traversal & Construct Binary Tree from Preorder and Inorder Traversal

    LeetCode 原题链接 Construct Binary Tree from Inorder and Postorder Traversal - LeetCode Construct Binary ...

随机推荐

  1. 继续ajax长轮询解决方案--递归

    如果使用for,会有一种情况发生,就是ajax的执行会大于其他的动作的执行,那么这样的一段代码就不能实现了 for(var i=0;i<20;i++){ console.log('你好') $. ...

  2. 风情万种awk

    awk是基于列的文本处理工具,所有的文件都是由单词和各种空白字符组成.这里"空白字符"包括空格.tab以及连续的空格和tab,每个非空白的部分叫做"域",从左到 ...

  3. UVA 548.Tree-fgets()函数读入字符串+二叉树(中序+后序遍历还原二叉树)+DFS or BFS(二叉树路径最小值并且相同路径值叶子节点权值最小)

    Tree UVA - 548 题意就是多次读入两个序列,第一个是中序遍历的,第二个是后序遍历的.还原二叉树,然后从根节点走到叶子节点,找路径权值和最小的,如果有相同权值的就找叶子节点权值最小的. 最后 ...

  4. ProgrammingProjectList-文本操作

    https://github.com/jobbole/ProgrammingProjectList 逆转字符串——输入一个字符串,将其逆转并输出. package com.zrl.github; im ...

  5. Java-多线程编程(一)

    创建多线程 [Thread class]1.继承Thread类,重写run() [Runnable接口]2.实现Runnable接口,重写run() [*Callable接口]3.实现Callable ...

  6. 基于SAAJ的客户端

    概述 SAAJ - SOAP with Attachments API for JAVA 结构图如下: 正文 1. 如何获取soap请求的关键参数 关键的参数有四个: xmlns - xml命名空间如 ...

  7. Oracle常用常考集合

    登陆远程服务器 sqlplus scott/tiger@192.168.2.1[:port]/sid [as sysdba] 简单查询 select  table_name from user_tab ...

  8. luogu P1060 开心的金明

    题目描述 金明今天很开心,家里购置的新房就要领钥匙了,新房里有一间他自己专用的很宽敞的房间.更让他高兴的是,妈妈昨天对他说:“你的房间需要购买哪些物品,怎么布置,你说了算,只要不超过N元钱就行”.今天 ...

  9. 【20181019T3】比特战争【最小生成树思想】

    题面 [错解] Hmm不可做啊 要不按b排个序? 然后并查集瞎搞,刷刷刷过了样例 然后大样例大了几万倍 出了组小数据,Successful Hack 弃疗 水过10分 [正解] 用占领的边将顶点连起来 ...

  10. BZOJ 2809 [Apio2012]dispatching(斜堆+树形DP)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=2809 [题目大意] 给出一棵树,求出每个点有个权值,和一个乘算值,请选取一棵子树, 并 ...