想必大家在刷leetcode时候,刷到特定的题目的时候都曾经看过这样的图片,这就是Binary tree,但在认识Binary tree之前,让我们先来认识tree这种资料结构吧!
图片来源:101. Symmetric Tree
是一种抽象的资料结构,由一个以上的节点所组成,每个节点可以有多个子节点,最顶端的根节点称为root ,最下面的层级的节点称为leaves(2, 1, 7 …)
图片来源:working-with-trees
而节点与节点之间的关系名词可以参考下图
图片来源:understanding-binary-search-trees-4d90
每个节点的子节点最少0个,最多2个 ,每个节点会纪录三种资料
图片来源:Binary Tree
与一般树的比较如下,Binary Tree每个节点最多就是两个子节点
图片来源:difference-between-general-tree-and-binary-tree
图片来源:5-types-of-binary-tree-with-cool-illustrations
full
Complete
Degenerate
Perfect
Balance
Skewed
具有Binary Tree的特性,每个节点的子节点不超过2个,除此之外,左边的子节点必定小於根节点,右边的子节点必定大於根节点,因此整棵树最左边的节点必定是最小的,最右边的节点必定是最大的,也因为Binary Search Tree这样的特性,所以不管是新增节点、删除节点、搜寻节点的时间复杂度都是O(log n)。
图片来源:implementing-binary-search-tree
用js实作出Binary Search Tree
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
this.queue = [];
}
insertNode(value) {
let current = new TreeNode(value);
let target = null;
let nowPos = this.root;
while (nowPos !== null) {
target = nowPos;
if (current.value < nowPos.value) {
nowPos = nowPos.left;
} else {
nowPos = nowPos.right;
}
}
if (target === null) {
this.root = current;
} else if (current.value < target.value) {
target.left = current;
} else {
target.right = current;
}
}
}
let tree = new BinarySearchTree();
tree.insertNode(10);
tree.insertNode(8);
tree.insertNode(11);
tree.insertNode(5);
tree.insertNode(9);
tree.insertNode(15);
tree.insertNode(2);
tree.insertNode(19);
tree.insertNode(13);
如果consolo.log(tree)可以看到我们成功用物件模拟出一颗Binary Search Tree
Binary Heaps又分为Min-Heaps 和 Max-Heaps,适合用来找最小值或最大值
图片来源:heap-data-structure
关於Heap Tree的实作会在之後的Heap Sort文章中介绍
参考资料: understanding-binary-search-trees
<<: 【Day 2】 Vim x Plugin x 准备主厨刀
初始控制 会利用某些手段达成RCE(Remote code execution,远端代码执行),方法...
引言 昨天学了 chmod 命令的用法,这边大概整理几个简单用法: $ chmod 参数 目标档案...
延续上一篇的 ViewModel 结构 现在假设使用者提出要动态 新增/删除 Collection ...
=x= 🌵 建立 News Manager - Content Page 後台页面 。 News M...
昨天将产出的验证码写进了 Google Sheet,但我们还需要另一个功能:输入验证码找出所在Row...