首頁 > web前端 > js教程 > 主體

在 JavaScript 中實作二元搜尋樹

WBOY
發布: 2023-08-30 09:25:02
轉載
428 人瀏覽過

在 JavaScript 中实现二叉搜索树

樹資料結構

樹是由一些邊連接的節點的集合。按照慣例,樹的每個節點 保存一些資料和對其子節點的引用。

二元搜尋樹

二元搜尋樹是一棵二元樹,其中具有較小值的節點儲存在左側,而具有較小值的節點儲存在左側。較高的值儲存在右側。

例如,有效 BST 的視覺表示是 -

     25
   /   \
  20   36
 / \   / \
10 22 30 40
登入後複製

現在讓我們用 JavaScript 語言實作我們自己的二元搜尋樹。

第 1 步:節點類別

該類別將表示存在於 BST 中各個點的單一節點。 BST 沒什麼 而是按照規則放置的儲存資料和子引用的節點的集合 如上所述。

class Node{
   constructor(data) {
      this.data = data;
      this.left = null;
      this.right = null;
   };
};
登入後複製

要建立一個新的Node 實例,我們可以使用一些資料來呼叫此類-

const newNode = new Node(23);
登入後複製

這將建立一個新的Node 實例,其資料設定為23,左右引用均為null。

第 2 步:二叉搜尋樹類:

class BinarySearchTree{
   constructor(){
      this.root = null;
   };
};
登入後複製

這將建立一個二元搜尋樹類,我們可以使用 new 關鍵字呼叫它來建立一個 樹實例。

現在我們已經完成了基本的工作,讓我們繼續在正確的位置插入一個新節點(根據定義中描述的 BST 規則)。

步驟3:在BST中插入節點

class BinarySearchTree{
   constructor(){
      this.root = null;
   }
   insert(data){
      var newNode = new Node(data);
      if(this.root === null){
         this.root = newNode;
      }else{
         this.insertNode(this.root, newNode);
      };
   };
   insertNode(node, newNode){
      if(newNode.data < node.data){
         if(node.left === null){
            node.left = newNode;
         }else{
            this.insertNode(node.left, newNode);
         };
      } else {
         if(node.right === null){
            node.right = newNode;
         }else{
            this.insertNode(node.right,newNode);
         };
      };
   };
};
登入後複製

範例

完整二叉搜尋樹碼:

class Node{
   constructor(data) {
      this.data = data;
      this.left = null;
      this.right = null;
   };
};
class BinarySearchTree{
   constructor(){
      this.root = null;
   }
   insert(data){
      var newNode = new Node(data);
      if(this.root === null){
         this.root = newNode;
      }else{
         this.insertNode(this.root, newNode);
      };
   };
   insertNode(node, newNode){
      if(newNode.data < node.data){
         if(node.left === null){
            node.left = newNode;
         }else{
            this.insertNode(node.left, newNode);
         };
      } else {
         if(node.right === null){
            node.right = newNode;
         }else{
            this.insertNode(node.right,newNode);
         };
      };
   };
};
const BST = new BinarySearchTree();
BST.insert(1);
BST.insert(3);
BST.insert(2);
登入後複製

以上是在 JavaScript 中實作二元搜尋樹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!