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. Optional int parameter 'id' is present but cannot be translated into a null value due to being decla

    这个错误可以将参数由int改为Integer

  2. 视频H5のVideo标签在微信里的坑和技巧

    随着 4G 的普遍以及 WiFi 的广泛使用,手机上的网速已经足够稳定和高速,以视频为主的 HTML5 也越来越普遍了,相比帧动画,视频的表现更加丰富,前段时间开发了一个以视频为主的移动端 HTML5 ...

  3. HRBUST 1217 统计单词个数

    $dp$. 设$dp[i][j]$为到$i$位置,切成了$j$段的最大收益,然后枚举一下$f$,$dp[i][j]=max(dp[f][j-1]+v[f+1][i])$.一段区间的价值可以用区间$dp ...

  4. 并发系列3-大白话聊聊Java并发面试问题之谈谈你对AQS的理解?【石杉的架构笔记】

  5. Web应用主动侦测工具Skipfish

    Web应用主动侦测工具Skipfish   Skipfish是Kali Linux附带的一个主动Web应用侦测工具.该工具会首先尽可能获取所有网站路径,进行访问,然后根据返回的内容,检测是否存在漏洞. ...

  6. [BZOJ4033][HAOI2015]树上染色(树形DP)

    4033: [HAOI2015]树上染色 Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 2437  Solved: 1034[Submit][Stat ...

  7. 【扫描线】Gym - 100781G - Goblin Garden Guards

    平面上有100000个哥布林和20000个圆,问你不在圆内的哥布林有多少个. 将每个圆从左到右切2r+1次,形成(2r+1)*2个端点,将上端点记作入点,下端点记作出点,再将这些点和那些哥布林一起排序 ...

  8. 【KMP求最小周期】POJ2406-Power Strings

    [题意] 给出一个字符串,求出最小周期. [思路] 对KMP的next数组的理解与运用orz ①证明:如果最小周期不等于它本身,则前缀和后缀必定有交叉. 如果没有交叉,以当前的next[n]为最小周期 ...

  9. 广义线性模型(logistic和softmax)

    再谈广义线性模型之前,先来看一下普通线性模型: 普通线性模型的假设主要有以下几点: 1.响应变量Y和误差项ϵ正态性:响应变量Y和误差项ϵ服从正态分布,且ϵ是一个白噪声过程,因而具有零均值,同方差的特性 ...

  10. Codeforces Round #341 (Div. 2) D. Rat Kwesh and Cheese 数学

    D. Rat Kwesh and Cheese 题目连接: http://www.codeforces.com/contest/621/problem/D Description Wet Shark ...