1、概念:二叉树是每个节点最多有两个子树的有序树。通常子树被称作“左子树”(left subtree)和“右子树”(right subtree)。二叉树常被用于实现二叉查找树和二叉堆。
2、原理(灵魂画手),如下数组,遍历生成二叉树,则可以得到升序
3、代码实现
class Node { //树节点
constructor(value) {
this.value = value
this.left = null
this.right = null
}
}
class NodeSearch { //搜索树
constructor() {
this.root = null
this.len = 0
}
add(key) { //生成节点
let node = new Node(key)
if(this.root) {
this.insertNode(this.root,node)
}else{
this.root = node
}
this.len++
return this
}
insertNode(root, node) { //插入节点
if(root.value > node.value) {
root.left ? this.insertNode(root.left,node) : root.left = node
}else{
root.right ? this.insertNode(root.right, node) : root.right = node;
}
}
toTree(arr) { //生成树
if(toString.call(arr) !== "[object Array]") return false
for(let i=0;i<arr.length;i++) {
this.add(arr[i])
}
}
toArray() {
let result = []
if(this.len > 0) {
const middleOrder = (root) => {
root.left && middleOrder(root.left);
result.push(root.value);
root.right && middleOrder(root.right);
return result;
};
return middleOrder(this.root);
}
}
}
let arr = [23,3,12,45,3]
let ns = new NodeSearch()
ns.toTree(arr)
console.log(ns.toArray())