当前位置:首页 > JavaScript

js实现tree

2026-04-04 09:58:38JavaScript

实现树结构的基本方法

使用JavaScript实现树结构通常需要定义节点类和树类。树结构由多个节点组成,每个节点包含数据和指向子节点的引用。

class TreeNode {
  constructor(data) {
    this.data = data;
    this.children = [];
  }

  addChild(child) {
    if (child instanceof TreeNode) {
      this.children.push(child);
    } else {
      this.children.push(new TreeNode(child));
    }
  }
}

class Tree {
  constructor() {
    this.root = null;
  }

  traverseDF(callback) {
    const traverse = (node) => {
      callback(node);
      node.children.forEach(child => traverse(child));
    };
    traverse(this.root);
  }

  traverseBF(callback) {
    const queue = [this.root];
    while (queue.length > 0) {
      const node = queue.shift();
      callback(node);
      queue.push(...node.children);
    }
  }
}

树的遍历方法

深度优先遍历(DFS)和广度优先遍历(BFS)是树结构的两种基本遍历方式。DFS会沿着树的深度遍历子节点,BFS会按层级遍历节点。

js实现tree

// 深度优先搜索示例
const dfs = (node) => {
  console.log(node.data);
  node.children.forEach(child => dfs(child));
};

// 广度优先搜索示例
const bfs = (root) => {
  const queue = [root];
  while (queue.length > 0) {
    const node = queue.shift();
    console.log(node.data);
    queue.push(...node.children);
  }
};

树的操作方法

树结构支持多种操作,包括查找节点、删除节点、计算深度等。

js实现tree

// 查找节点
Tree.prototype.find = function(data, traversal) {
  let result = null;
  traversal.call(this, (node) => {
    if (node.data === data) {
      result = node;
    }
  });
  return result;
};

// 计算树的高度
Tree.prototype.getHeight = function() {
  const getMaxDepth = (node) => {
    if (!node || node.children.length === 0) return 0;
    const depths = node.children.map(child => getMaxDepth(child));
    return Math.max(...depths) + 1;
  };
  return getMaxDepth(this.root);
};

二叉树实现

二叉树是每个节点最多有两个子节点的树结构,常用于搜索和排序算法。

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

class BinaryTree {
  constructor() {
    this.root = null;
  }

  insert(value) {
    const newNode = new BinaryTreeNode(value);
    if (!this.root) {
      this.root = newNode;
      return;
    }

    let current = this.root;
    while (true) {
      if (value < current.value) {
        if (!current.left) {
          current.left = newNode;
          return;
        }
        current = current.left;
      } else {
        if (!current.right) {
          current.right = newNode;
          return;
        }
        current = current.right;
      }
    }
  }
}

树的可视化表示

将树结构转换为可视化格式有助于调试和理解树的状态。

Tree.prototype.toString = function() {
  const lines = [];
  const traverse = (node, prefix) => {
    lines.push(prefix + node.data);
    node.children.forEach((child, i) => {
      const isLast = i === node.children.length - 1;
      traverse(child, prefix + (isLast ? '└── ' : '├── '));
    });
  };
  traverse(this.root, '');
  return lines.join('\n');
};

标签: jstree
分享给朋友:

相关文章

js实现轮播图

js实现轮播图

轮播图实现方法 基础HTML结构 <div class="slider"> <div class="slides"> <img src="image1.jpg…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现类

js实现类

JavaScript 实现类的几种方式 JavaScript 是一种基于原型的语言,但在 ES6 之后引入了 class 语法糖,使得实现类更加直观。以下是几种常见的实现方式: 使用构造函数 传统的…

js实现变形

js实现变形

使用 CSS 和 JavaScript 实现元素变形 在 JavaScript 中实现变形效果通常结合 CSS 的 transform 属性,通过动态修改该属性实现元素的旋转、缩放、倾斜或平移。 基…

js实现目录

js实现目录

实现目录的基本思路 在JavaScript中实现目录功能通常涉及以下几个核心步骤:解析文档中的标题元素(如h1-h6),动态生成目录结构,并添加交互逻辑(如点击跳转)。以下是具体实现方法: 解析标题…

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…