JS树形数据常用递归方法总结




// 定义一个树形结构的函数
function Tree() {
  const nodes = new Map();
 
  // 添加节点
  this.add = function(parent, id) {
    nodes.set(id, { parent, children: new Set() });
  };
 
  // 移除节点
  this.remove = function(id) {
    nodes.delete(id);
    // 还需要从其父节点的children中移除
  };
 
  // 获取所有子孙节点
  this.getSubtree = function(id) {
    const subtree = new Set([id]);
    const dfs = (nodeId) => {
      nodes.get(nodeId).children.forEach(child => {
        subtree.add(child);
        dfs(child);
      });
    };
    nodes.get(id).children.forEach(dfs);
    return subtree;
  };
 
  // 获取所有祖先节点
  this.getAncestors = function(id) {
    const ancestors = new Set();
    let node = nodes.get(id);
    while (node.parent) {
      ancestors.add(node.parent);
      node = nodes.get(node.parent);
    }
    return ancestors;
  };
 
  // 检查是否为叶子节点
  this.isLeaf = function(id) {
    return nodes.get(id).children.size === 0;
  };
 
  // 检查是否为根节点
  this.isRoot = function(id) {
    return !nodes.get(id).parent;
  };
 
  // 获取树的深度
  this.getDepth = function() {
    let depth = 0;
    // 需要遍历所有节点并更新depth
    return depth;
  };
}
 
// 使用示例
const tree = new Tree();
tree.add(null, 'A');
tree.add('A', 'B');
tree.add('A', 'C');
tree.add('B', 'D');
tree.add('B', 'E');
tree.add('C', 'F');
 
console.log(tree.getSubtree('A')); // 输出节点A的所有子孙节点
console.log(tree.getAncestors('D')); // 输出节点D的所有祖先节点
console.log(tree.isLeaf('B')); // 输出节点B是否为叶子节点
console.log(tree.isRoot('D')); // 输出节点D是否为根节点
// 注意: 需要实现getDepth方法来获取树的深度

这个代码示例展示了如何实现一个简单的树形数据结构,并提供了几个常用的递归方法,如获取子孙节点、祖先节点,检查叶子和根节点,以及计算树的深度。需要注意的是,示例中的getDepth方法尚未实现,因为它需要遍历所有节点并更新最大深度。

最后修改于:2024年08月18日 22:57

评论已关闭

推荐阅读

Vue中使用mind-map实现在线思维导图
2024年08月04日
VUE
Web前端最全Vue实现免密登录跳转的方式_vue怎么样不登录返回首页,最强技术实现
2024年08月04日
VUE
vue3 项目搭建教程(基于create-vue,vite,Vite + Vue)
2024年08月04日
VUE
Vue-颜色选择器实现方案——>Vue-Color( 实战*1+ Demo*7)
2024年08月04日
VUE
Vue项目卡顿慢加载?这些优化技巧告诉你!_vue数据多渲染卡顿
2024年08月04日
VUE
vue中的keep-alive详解与应用场景
2024年08月04日
VUE
Vue、React实现excel导出功能(三种实现方式保姆级讲解)
2024年08月04日
vue-office/docx插件实现docx文件预览
2024年08月04日
VUE
java调用js文件的两种方法(支持V8引擎)
2024年08月04日
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2024年08月04日
两周从爬虫小白变大神 _yjs_js_security_passport
2024年08月04日
JS笔记(对象、函数、数组)
2024年08月04日
Markdown.js:强大的纯JavaScript Markdown解析器
2024年08月04日
Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
2024年08月04日
vue 父组件怎么获取子组件里面的data数据
2024年08月04日
VUE
个人开发实现AI套壳网站快速搭建(Vue+elementUI+SpringBoot)
2024年08月04日
el-table 表格封装并改造实现单元格可编辑
2024年08月04日
none
nodejs环境下创建vue项目、SSH密钥登陆!!!
2024年08月04日
vue+quill+element-ui实现视频、图片上传及缩放保姆级教程,轻松使用富文本
2024年08月04日
【three.js】22. Imported Models导入模型
2024年08月04日