<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//定义节点
//
class Node {
constructor(key) {
this.key = key; // 节点值
this.left = null; // 左指针
this.right = null; // 右指针
}
}
class NodeTree {
constructor() {
this.root = null;
this.list = []; //排序数组
}
//二叉树结构
insertNodeParents(data) {
const newNode = new Node(data)
if (this.root == null) this.root = newNode
else this.insertNode(this.root, newNode)
}
//二叉树结构
insertNode(root, newNode) {
if (root.key >= newNode.key) {
if (root.left == null) root.left = newNode
else this.insertNode(root.left, newNode)
} else {
if (root.right == null) root.right = newNode
else this.insertNode(root.right, newNode)
}
}
//二叉树中序遍历
sortingNodes() {
this.sortingNode(this.root)
}
sortingNode(root) {
if (root) {
this.sortingNode(root.right)
this.list.push(root.key)
this.sortingNode(root.left)
}
}
//二叉树前序遍历
sortingNodeBefore() {
this.sortingNodeBefores(this.root)
}
sortingNodeBefores(root) {
if (root) {
console.log('left: ', root.key);
this.sortingNodeBefores(root.left)
this.sortingNodeBefores(root.right)
}
}
//二叉树后序遍历
sortingNodeAfter() {
this.sortingNodeAfters(this.root)
}
sortingNodeAfters(root) {
if (root) {
this.sortingNodeAfters(root.left)
this.sortingNodeAfters(root.right)
console.log('left: ', root.key);
}
}
//查找最大值
getMax(root = this.root) {
if (root.right == null) {
return root.key
}
return this.getMax(root.right)
}
//查找最小值
getMin(root = this.root) {
if (root.left == null) {
return root.key
}
return this.getMin(root.left)
}
//查找某一个值
getSpecified(value) {
return this.getSpecifieds(this.root, value)
}
getSpecifieds(root, value) {
if (root == null) return false
if (root.key > value) {
return this.getSpecifieds(root.left, value)
} else if (root.key < value) {
return this.getSpecifieds(root.right, value)
}
return true
}
}
const xcq = new NodeTree()
const list = [19, 8, 5, 15, 12, 24, 45]
list.forEach(i => xcq.insertNodeParents(i))
xcq.sortingNodes(node => node.key)
let max = xcq.getMax()
let getMin = xcq.getMin()
xcq.sortingNodeBefore()
xcq.sortingNodeAfter()
let isHas = xcq.getSpecified(11229)
console.log('isHas: ', isHas);
console.log('getMin: ', getMin);
console.log('max: ', max);
console.log(xcq)
</script>
</body>
</html>