持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第25天。
树是一种分层数据的抽象模型。现实中常见的比如公司的组织架构图:
相关术语
- 节点:树中的每个元素都叫节点,也称为键
- 根节点:树顶部的节点。没有父节点
- 内部节点:至少有一个子节点的节点
- 外部节点(叶节点):没有子节点的节点
- 子树:子树由节点和它的后代构成
- 深度:取决于它的祖先节点的数量
- 高度:取决于所有节点深度的最大值
- 边:表示节点之间的关系(即指针),一个指向左侧子节点,一个指向右侧子节点
二叉树
- 二叉树:二叉树中的节点最多只能有两个子节点。
- 二叉搜索树:二叉树的一种。只允许在左侧节点存储比父节点小的值,右侧节点存储比父节点大的值。
实现代码: util.js
// 判断是左节点还是右节点的工具方法
export const Compare = {
LESS_THAN: -1,
BIGGER_THAN: 1,
EQUAL_THAN: 0
}
export function defaultCompare(a, b) {
if (a === b) {
return Compare.EQUAL_THAN;
}
return a < b ? Compare.LESS_THAN : Compare.BIGGER_THAN;
}
Node.js
// 节点类
export class Node{
constructor(key){
this.key = key
this.left = null
this.right = null
}
}
searchTree.js
// 创建二叉树并插入值
import { Compare, defaultCompare } from './util.js'
import { Node } from './Node.js'
export default class BinarySearchTree{
constructor(compareFn = defaultCompare){
this.compareFn = compareFn
this.root = null
}
// 插入节点
insert(key){
if(this.root == null){
this.root = new Node(key)
} else {
this.insertNode(this.root, key)
}
}
insertNode(node, key){
if(this.compareFn(key, node.key) === Compare.LESS_THAN){
if(node.left == null){
node.left = new Node(key)
} else {
this.insertNode(node.left, key)
}
} else {
if(node.right == null){
node.right = new Node(key)
} else {
this.insertNode(node.right, key)
}
}
}
}
const tree = new BinarySearchTree()
tree.insert(11)
tree.insert(10)
tree.insert(15)
console.log(tree)
树的遍历
树的遍历方法有三种:
- 中序
- 先序
- 后序