亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
? Implementing a Basic Tree
? Binary Tree & Binary Search Tree (BST)
? Implementing Graphs
Undirected, Unweighted Graph
? Tips & Best Practices
首頁 web前端 js教程 JavaScript數(shù)據(jù)結(jié)構(gòu):實(shí)現(xiàn)樹和圖形

JavaScript數(shù)據(jù)結(jié)構(gòu):實(shí)現(xiàn)樹和圖形

Aug 01, 2025 am 04:55 AM

樹和圖可通過對象和引用在JavaScript中實(shí)現(xiàn);2. 樹結(jié)構(gòu)如TreeNode類支持 addChild、removeChild 和 DFS 遍歷;3. 二叉搜索樹(BST)通過左小右大規(guī)則實(shí)現(xiàn)高效查找、插入和中序遍歷;4. 圖使用鄰接表(Map Set)表示,支持添加頂點(diǎn)和邊、BFS和DFS遍歷;5. 實(shí)踐建議包括用Set避免重復(fù)邊、迭代避免棧溢出、根據(jù)場景選擇BFS或DFS,最終可擴(kuò)展至加權(quán)圖或算法應(yīng)用。

JavaScript Data Structures: Implementing Trees and Graphs

Trees and graphs are fundamental data structures in computer science, and while JavaScript doesn’t provide built-in classes for them, implementing them is straightforward and highly practical for solving real-world problems like file system navigation, organizational hierarchies, social networks, or routing algorithms.

JavaScript Data Structures: Implementing Trees and Graphs

Let’s walk through how to implement trees and graphs in JavaScript, focusing on clarity, usability, and common patterns.


? Implementing a Basic Tree

A tree is a hierarchical structure where each node has a value and zero or more children. A common type is the n-ary tree, where each node can have multiple children.

JavaScript Data Structures: Implementing Trees and Graphs
class TreeNode {
  constructor(value) {
    this.value = value;
    this.children = [];
  }

  addChild(value) {
    const childNode = new TreeNode(value);
    this.children.push(childNode);
    return childNode;
  }

  removeChild(value) {
    this.children = this.children.filter(child => child.value !== value);
  }

  // Traverse and print values (DFS)
  print(level = 0) {
    console.log("  ".repeat(level)   this.value);
    this.children.forEach(child => child.print(level   1));
  }
}

Usage Example:

const root = new TreeNode("A");
const b = root.addChild("B");
const c = root.addChild("C");
b.addChild("D");
b.addChild("E");
c.addChild("F");

root.print();
// Output:
// A
//   B
//     D
//     E
//   C
//     F

This structure is great for representing nested data like folders, comments in a thread, or DOM elements.

JavaScript Data Structures: Implementing Trees and Graphs

? Binary Tree & Binary Search Tree (BST)

A binary tree restricts nodes to at most two children: left and right. A Binary Search Tree (BST) adds ordering: left < parent < right.

class BSTNode {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }

  insert(value) {
    if (value < this.value) {
      if (this.left === null) {
        this.left = new BSTNode(value);
      } else {
        this.left.insert(value);
      }
    } else {
      if (this.right === null) {
        this.right = new BSTNode(value);
      } else {
        this.right.insert(value);
      }
    }
  }

  search(value) {
    if (value === this.value) return true;
    if (value < this.value && this.left) return this.left.search(value);
    if (value > this.value && this.right) return this.right.search(value);
    return false;
  }

  // In-order traversal (left → root → right)
  inOrder(values = []) {
    if (this.left) this.left.inOrder(values);
    values.push(this.value);
    if (this.right) this.right.inOrder(values);
    return values;
  }
}

Usage Example:

const bst = new BSTNode(10);
[5, 15, 3, 7, 12, 18].forEach(val => bst.insert(val));

console.log(bst.search(7));     // true
console.log(bst.search(9));     // false
console.log(bst.inOrder());     // [3, 5, 7, 10, 12, 15, 18]

BSTs are efficient for searching, insertion, and deletion (average O(log n)) when balanced.


? Implementing Graphs

A graph consists of nodes (vertices) connected by edges. Graphs can be:

  • Directed or undirected
  • Weighted or unweighted

We’ll use an adjacency list representation — a map where each key is a node, and its value is an array (or set) of connected nodes.

Undirected, Unweighted Graph

class Graph {
  constructor() {
    this.adjacencyList = new Map();
  }

  addVertex(vertex) {
    if (!this.adjacencyList.has(vertex)) {
      this.adjacencyList.set(vertex, new Set());
    }
  }

  addEdge(v1, v2) {
    this.addVertex(v1);
    this.addVertex(v2);
    this.adjacencyList.get(v1).add(v2);
    this.adjacencyList.get(v2).add(v1); // Remove this line for directed graph
  }

  removeEdge(v1, v2) {
    this.adjacencyList.get(v1)?.delete(v2);
    this.adjacencyList.get(v2)?.delete(v1);
  }

  removeVertex(vertex) {
    if (!this.adjacencyList.has(vertex)) return;

    for (const adjacent of this.adjacencyList.get(vertex)) {
      this.removeEdge(vertex, adjacent);
    }
    this.adjacencyList.delete(vertex);
  }

  // BFS traversal
  breadthFirst(start) {
    const queue = [start];
    const visited = new Set();
    const result = [];

    visited.add(start);

    while (queue.length > 0) {
      const vertex = queue.shift();
      result.push(vertex);

      for (const neighbor of this.adjacencyList.get(vertex)) {
        if (!visited.has(neighbor)) {
          visited.add(neighbor);
          queue.push(neighbor);
        }
      }
    }

    return result;
  }

  // DFS traversal (iterative)
  depthFirst(start) {
    const stack = [start];
    const visited = new Set();
    const result = [];

    visited.add(start);

    while (stack.length > 0) {
      const vertex = stack.pop();
      result.push(vertex);

      for (const neighbor of this.adjacencyList.get(vertex)) {
        if (!visited.has(neighbor)) {
          visited.add(neighbor);
          stack.push(neighbor);
        }
      }
    }

    return result;
  }
}

Usage Example:

const graph = new Graph();
graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("B", "D");
graph.addEdge("C", "D");
graph.addEdge("D", "E");

console.log(graph.breadthFirst("A")); // ['A', 'B', 'C', 'D', 'E']
console.log(graph.depthFirst("A"));  // ['A', 'C', 'D', 'E', 'B'] (order may vary)

This implementation is flexible — you can easily extend it to support directed or weighted edges.


? Tips & Best Practices

  • Use Sets for adjacency lists to avoid duplicate edges.
  • For weighted graphs, store edges as objects: { node: 'B', weight: 5 }
  • Always handle edge cases like missing nodes or disconnected graphs.
  • Choose BFS for shortest path in unweighted graphs; DFS for deep exploration.
  • Consider recursion for tree traversals, but use iteration for large graphs to avoid stack overflow.

Basically, trees and graphs in JavaScript come down to linking objects (nodes) and managing connections. Once you understand the patterns, you can adapt them to everything from autocomplete (tries) to network routing (Dijkstra’s algorithm). Not hard to start with — just build node by node.

以上是JavaScript數(shù)據(jù)結(jié)構(gòu):實(shí)現(xiàn)樹和圖形的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
如何在node.js中提出HTTP請求? 如何在node.js中提出HTTP請求? Jul 13, 2025 am 02:18 AM

在Node.js中發(fā)起HTTP請求有三種常用方式:使用內(nèi)置模塊、axios和node-fetch。1.使用內(nèi)置的http/https模塊無需依賴,適合基礎(chǔ)場景,但需手動(dòng)處理數(shù)據(jù)拼接和錯(cuò)誤監(jiān)聽,例如用https.get()獲取數(shù)據(jù)或通過.write()發(fā)送POST請求;2.axios是基于Promise的第三方庫,語法簡潔且功能強(qiáng)大,支持async/await、自動(dòng)JSON轉(zhuǎn)換、攔截器等,推薦用于簡化異步請求操作;3.node-fetch提供類似瀏覽器fetch的風(fēng)格,基于Promise且語法簡單

JavaScript數(shù)據(jù)類型:原始與參考 JavaScript數(shù)據(jù)類型:原始與參考 Jul 13, 2025 am 02:43 AM

JavaScript的數(shù)據(jù)類型分為原始類型和引用類型。原始類型包括string、number、boolean、null、undefined和symbol,其值不可變且賦值時(shí)復(fù)制副本,因此互不影響;引用類型如對象、數(shù)組和函數(shù)存儲(chǔ)的是內(nèi)存地址,指向同一對象的變量會(huì)相互影響。判斷類型可用typeof和instanceof,但需注意typeofnull的歷史問題。理解這兩類差異有助于編寫更穩(wěn)定可靠的代碼。

JavaScript時(shí)間對象,某人構(gòu)建了一個(gè)eactexe,在Google Chrome上更快的網(wǎng)站等等 JavaScript時(shí)間對象,某人構(gòu)建了一個(gè)eactexe,在Google Chrome上更快的網(wǎng)站等等 Jul 08, 2025 pm 02:27 PM

JavaScript開發(fā)者們,大家好!歡迎閱讀本周的JavaScript新聞!本周我們將重點(diǎn)關(guān)注:Oracle與Deno的商標(biāo)糾紛、新的JavaScript時(shí)間對象獲得瀏覽器支持、GoogleChrome的更新以及一些強(qiáng)大的開發(fā)者工具。讓我們開始吧!Oracle與Deno的商標(biāo)之爭Oracle試圖注冊“JavaScript”商標(biāo)的舉動(dòng)引發(fā)爭議。Node.js和Deno的創(chuàng)建者RyanDahl已提交請?jiān)笗?,要求取消該商?biāo),他認(rèn)為JavaScript是一個(gè)開放標(biāo)準(zhǔn),不應(yīng)由Oracle

什么是緩存API?如何與服務(wù)人員使用? 什么是緩存API?如何與服務(wù)人員使用? Jul 08, 2025 am 02:43 AM

CacheAPI是瀏覽器提供的一種緩存網(wǎng)絡(luò)請求的工具,常與ServiceWorker配合使用,以提升網(wǎng)站性能和離線體驗(yàn)。1.它允許開發(fā)者手動(dòng)存儲(chǔ)如腳本、樣式表、圖片等資源;2.可根據(jù)請求匹配緩存響應(yīng);3.支持刪除特定緩存或清空整個(gè)緩存;4.通過ServiceWorker監(jiān)聽fetch事件實(shí)現(xiàn)緩存優(yōu)先或網(wǎng)絡(luò)優(yōu)先等策略;5.常用于離線支持、加快重復(fù)訪問速度、預(yù)加載關(guān)鍵資源及后臺(tái)更新內(nèi)容;6.使用時(shí)需注意緩存版本控制、存儲(chǔ)限制及與HTTP緩存機(jī)制的區(qū)別。

處理諾言:鏈接,錯(cuò)誤處理和承諾在JavaScript中 處理諾言:鏈接,錯(cuò)誤處理和承諾在JavaScript中 Jul 08, 2025 am 02:40 AM

Promise是JavaScript中處理異步操作的核心機(jī)制,理解鏈?zhǔn)秸{(diào)用、錯(cuò)誤處理和組合器是掌握其應(yīng)用的關(guān)鍵。1.鏈?zhǔn)秸{(diào)用通過.then()返回新Promise實(shí)現(xiàn)異步流程串聯(lián),每個(gè).then()接收上一步結(jié)果并可返回值或Promise;2.錯(cuò)誤處理應(yīng)統(tǒng)一使用.catch()捕獲異常,避免靜默失敗,并可在catch中返回默認(rèn)值繼續(xù)流程;3.組合器如Promise.all()(全成功才成功)、Promise.race()(首個(gè)完成即返回)和Promise.allSettled()(等待所有完成)

利用Array.Prototype方法用于JavaScript中的數(shù)據(jù)操作 利用Array.Prototype方法用于JavaScript中的數(shù)據(jù)操作 Jul 06, 2025 am 02:36 AM

JavaScript數(shù)組內(nèi)置方法如.map()、.filter()和.reduce()可簡化數(shù)據(jù)處理;1).map()用于一對一轉(zhuǎn)換元素生成新數(shù)組;2).filter()按條件篩選元素;3).reduce()用于聚合數(shù)據(jù)為單一值;使用時(shí)應(yīng)避免誤用導(dǎo)致副作用或性能問題。

JS綜述:深入研究JavaScript事件循環(huán) JS綜述:深入研究JavaScript事件循環(huán) Jul 08, 2025 am 02:24 AM

JavaScript的事件循環(huán)通過協(xié)調(diào)調(diào)用棧、WebAPI和任務(wù)隊(duì)列來管理異步操作。1.調(diào)用棧執(zhí)行同步代碼,遇到異步任務(wù)時(shí)交由WebAPI處理;2.WebAPI在后臺(tái)完成任務(wù)后將回調(diào)放入相應(yīng)的隊(duì)列(宏任務(wù)或微任務(wù));3.事件循環(huán)檢查調(diào)用棧是否為空,若為空則從隊(duì)列中取出回調(diào)推入調(diào)用棧執(zhí)行;4.微任務(wù)(如Promise.then)優(yōu)先于宏任務(wù)(如setTimeout)執(zhí)行;5.理解事件循環(huán)有助于避免阻塞主線程并優(yōu)化代碼執(zhí)行順序。

了解事件在JavaScript DOM事件中冒泡和捕獲 了解事件在JavaScript DOM事件中冒泡和捕獲 Jul 08, 2025 am 02:36 AM

事件冒泡是從目標(biāo)元素向外傳播到祖先節(jié)點(diǎn),事件捕獲則是從外層向內(nèi)傳播到目標(biāo)元素。1.事件冒泡:點(diǎn)擊子元素后,事件依次向上觸發(fā)父級元素的監(jiān)聽器,例如點(diǎn)擊按鈕后先輸出Childclicked,再輸出Parentclicked。2.事件捕獲:設(shè)置第三個(gè)參數(shù)為true,使監(jiān)聽器在捕獲階段執(zhí)行,如點(diǎn)擊按鈕前先觸發(fā)父元素的捕獲監(jiān)聽器。3.實(shí)際用途包括統(tǒng)一管理子元素事件、攔截預(yù)處理和性能優(yōu)化。4.DOM事件流分為捕獲、目標(biāo)和冒泡三個(gè)階段,默認(rèn)監(jiān)聽器在冒泡階段執(zhí)行。

See all articles