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. web前端零基础入门学习!前端真不难!

    现在互联网发展迅速,前端也成了很重要的岗位之一,许多人都往前端靠拢,可又无能为力,不知所措,首先我们说为什么在编程里,大家都倾向于往前端靠呢?原因很简单,那就是,在程序员的世界里,前端开发是最最简单的 ...

  2. java.util.regex包下的Pattern和Matcher详解(正则匹配)

    java正则表达式通过java.util.regex包下的Pattern类与Matcher类实现(建议在阅读本文时,打开java API文档,当介绍到哪个方法时,查看java API中的方法说明,效果 ...

  3. C# For Bot Framework

    Bot Framework是一个聊天机器人的框架,背后是微软的SDK,它可以使用C#和Nodejs开发,今天我尝试用创建一个比较简单Bot 参考地址:https://docs.microsoft.co ...

  4. Codeforces Round #119 (Div. 2) Cut Ribbon(DP)

    Cut Ribbon time limit per test 1 second memory limit per test 256 megabytes input standard input out ...

  5. Memory Allocation with COBOL

    Generally, the use of a table/array (Static Memory) is most common in COBOL modules in an applicatio ...

  6. Python - 字符和字符值之间的转换

    字符和字符值之间的转换 Python中, 字符和字符值, 直接的转换, 包含ASCII码和字母之间的转换,Unicode码和数字之间的转换; 也可以使用map, 进行批量转换, 输出为集合, 使用jo ...

  7. Standard Java集合类问题待整理

    1. HashSet.LinkedHashSet和TreeSet HashSet采用散列函数对元素进行排序,是专门为快速查询而设计的.存入HashSet的对象必须定义hashCode方法. TreeS ...

  8. [Codeforces 1053C] Putting Boxes Together

    Link: Codeforces 1053C 传送门 Solution: 先推出一个结论: 最后必有一个点不动且其为权值上最中间的一个点 证明用反证证出如果不在中间的点必有一段能用代价少的替代多的 这 ...

  9. 【找规律】【二进制拆分】hdu6129 Just do it

    给你数列a,问你对它作m次求前缀异或和之后的新数列是什么. 考虑a1对最终生成的数列的每一位的贡献,仅仅考虑奇偶性, 当m为2的幂次的时候,恰好是这样的 2^0 1 1 1 1 1 ... 2^1 1 ...

  10. 【预处理】Codeforces Round #407 (Div. 2) C. Functions again

    考虑枚举每个子串开头的位置,然后答案转化成询问这个位置之后 哪个位置的前缀和 - 这位置的前缀和 最大(当然是已经把绝对值和正负的情况处理好了,可以发现按奇偶,这个序列只有两种情况),只需要预处理这两 ...