二叉树中的节点最多只能有两个子节点:一个是左侧子节点,另一个是右侧子节点。而二叉搜索树又可以简称BST,它是二叉树的一种,但是只允许你在左侧节点存储(比父节点)小的值,在右侧节点存储(比父节点)大的值。
首先我们需要创建一个节点类用于存储节点数据以及它的左右子节点:
- class Node {
- constructor(key) {
- this.key = key;
- this.left = null;
- this.right = null;
- }
- }
然后需要创建一个二叉搜索树类,并且实现二叉搜索树的初步构建:
- class BinaryTree {
- constructor() {
- this.root = null;
- }
- // 插入
- insert(key) {
- const newNode = new Node(key);
- if (this.root === null) {
- this.root = newNode;
- }
- this.inertNode(this.root, newNode);
- }
- inertNode(node, newNode) {
- // 判断是放在左边还是右边
- // 如果插入的节点的值小于节点值则进入左子树
- if (newNode.key < node.key) {
- // 直到左子树为空
- if (node.left =