JS 遍历树

JavaScript 递归构建树形结构详解 我将详细讲解如何使用纯 JavaScript 递归方法将扁平数据转换为树形结构,并解释两种实现方式的原理和区别。 阅读详情

这几天一直在研究js,今天写一个关于js遍历树的JS程序:

  1. 关于树形结构的介绍:
    一般的树形结构如下,存在着父子,兄弟关系,其实这也是一种数学模型;常见的树有:二叉树【图1】、多
    叉树【图2】;
col 3 is这里写图片描述
图1图2

=====二叉树是多叉树的特例;
2. 结合上图二叉树有三种遍历方式:
前序:GDBEACF;
中序:ABDGECF;
后续:GDEBFCA;
=====在此多叉树没有左右子树之分,也就没有严格意义上的三种遍历方式,但还可以有其中前序,后续遍历;
3. 多叉树遍历的JS实现如下:
在此将上述多叉树的数据存储为JSON如下:
这里写图片描述

    /**数据格式决定算法设计:*/
    /**前序遍历
    */
    var scanStr=""; 
    function scan1(root){
        var text = root.text;
        var children = root.children;
        scanStr+=text;
        if(children != null)
        {
            for(var i in children)
                scan1(children[i]);
        }
    }
    /**后序遍历
    */
    function scan2(root){
        var children = root.children;   
        if(children != null){
            for(var i in children)//扫描孩子节点
                scan2(children[i]);
        //  scanStr+=root.text; 
        //}else{//是叶子节点了
        //  scanStr+=root.text; 
        }
        scanStr+=root.text; 
    }

引申》》》》》》》》》》 树的生成方式《《《《《《《《《《《
递归的方式查询数据生成树;
以层次的方式生成树;
【生成方式也不例外,要根据给出的原数据的格式来决定采用何种方式来生成树】
引申》》》》》》》》》》树的节点移动《《《《《《《《《《《

function moveNode(root){
        var children = root.children;
        var attr = root.attr;

        if(children != null){
            for(var i in children)//扫描孩子节点
                moveNode(children[i]);

            if(attr == 0){
                var parent = root.p;
                parentRemoveNode(parent,root);//父节点先移除

                var c = root.children;
                if(c!=null)
                parentAppendNode(parent,c);     
            }   

        }else{
            if(attr == 0){
                var parent = root.p;
                parentRemoveNode(parent,root);//父节点先移除

                var c = root.children;
                if(c!=null)
                parentAppendNode(parent,c); 
            }
        }
    }

    //设置parentNode ;root 的parent 为Null
    function setParentNode(root){
        var children = root.children;
        if(children != null)
        {
            for(var i in children){
                var c = children[i];
                    c.p = root;
                setParentNode(c);
            }
        }
    }

    /**父节点数组中删除一个节点
    */
    function parentRemoveNode(parent,node){ 
        var c = parent.children;
        if(c == null)
            return ;


        var nodeId = node.id;
        for(var i=0;i<c.length;i++){            
            var id = c[i].id;
            if(nodeId == id){//找到了
                c.splice(i,1);
            //  alert("移除:"+node.text+" "+node.id+" "+parent.length);
                break ;//删除完毕,打断
            }
        }
        //alert(JSON.stringify(parent));
    }
    /**将多个节点放到父节点下
    */
    function parentAppendNode(parent,children)
    {
        for(var i=0;i<children.length;i++)
            children[i].p = parent;//重新设置父节点
        parent.children = parent.children.concat(children);//两个数组合并 //合并后重新赋值
    }

关于上述代码的实例:

【JavaScript 算法】树的遍历:前序、中序与后序 树的遍历是指按照某种顺序访问树中的每一个节点。常见的树的遍历方法有三种:前序遍历(Preorder Traversal)、中序遍历(Inorder Traversal)和后序遍历(Postorder Traversal)。本文将详细介绍这三种遍历方法的原理、实现及其应用。 阅读详情

相关推荐

javascript如何用递归写一个简单的树形结构示例

现在有一个数据,需要你渲染出对应的列表出来: var data = [ {"id":1}, {"id":2}, {"id":3}, {"id":4}, ]; var str=""; data.forEach(function(v,i){ str+=""+v.id+"" }) str="" $(doucment).append(str); 哼,easy! 语罢,又是一道题飞来! 哦,还带了儿子来当帮手。我一个循环再一个循环,轻松带走你们 var data2 = [ {"id":1,children:[{"id":

JS递归遍历树结构

JS递归遍历树结构。

qq_45952585的博客 6024

如何用DETR(detection transformer)训练自己的数据集

DETR(detection transformer)简介 DETR是Facebook AI的研究者提出的Transformer的视觉版本,是CNN和transformer的融合,实现了端到端的预测,主要用于目标检测和全景分割。 DETR的Github地址:link

weixin_50233398的博客 3万+

js树结构数据的递归操作

1、获取树中的所有祖先节点名称 2、根据过滤条件筛选出需要留下节点的树结构数据 3、获取树中叶子节点的总个数 4、重新组合树结构中的数据 5、根据id和pid把json结构 转 树状结构

winne雪 2万+

使用PlotNeuralNet绘制深度学习网络图的基本操作

使用PlotNeuralNet绘制深度学习网络图的基本操作

weixin_46877907的博客 2110

随机森林文本分类

随机森林原理及代码实现 提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 例如:第一章 Python 机器学习入门之pandas的使用 提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录随机森林原理及代码实现前言一、集成算法是什么?二、随机森林是什么三、 数据预处理3.1 先来看一下我们的文本数据3.2 预处理3.3 统计评论情感值积极与消极的占比二、使用步骤参数介绍(4个)属性1.引入库2.参数调参方法总结 前言 提示:这里可以添加本文要记录的大概内容: 例如

m0_46579176的博客 5808

Web前端之JavaScript使用递归遍历树形结构数据、搜索、查询、查找、全值、find、instanceof

Web前端之JavaScript使用递归遍历树形结构数据、搜索、查询、查找、全值、find、instanceof

优快云博客主页地址:https://mengjian.blog.youkuaiyun.com/ 1万+

ROS2_IGH方案配置(二)——Ubuntu22.04 实时内核性能验证与调优

本文详细介绍了在Ubuntu22.04系统上配置ROS2_IGH方案时,如何验证和调优PREEMPT_RT实时内核性能。通过使用cyclictest工具进行基准测试和压力测试,分析中断与硬件延迟,并优化内核参数,确保系统满足工业控制领域对硬实时性的苛刻要求。文章还提供了针对ROS2的特殊优化建议和性能监控方案,帮助开发者实现毫秒级延迟的稳定控制。

weixin_30791095的博客 224

JS树的遍历

先序、中序、后序、层次遍历: //树的数据结构 function TreeNode(x){ this.val = x; this.left = null; this.right = null; } //先序遍历(Degree Left Right) function DLR(root){ console.log(root.val); if(root.lef...

封狼居胥 799

大模型-CLIP 详细介绍

最先进的计算机视觉系统通常被训练来预测一组预定义的对象类别。这种受限的监督形式限制了它们的通用性和可用性,因为要指定任何其他视觉概念,就需要额外的标注数据。比如,它们可以识别“猫”、“狗”、“汽车”等。但是,这种做法有一个明显的局限性:如果你想让系统识别一个新的类别,比如说“独角兽”,你就必须提供大量带有“独角兽”标签的图片来训练系统。这不仅耗时费力,而且限制了系统的灵活性和广泛适用性。直接从原始文本中学习关于图像的信息是一种很有前途的替代方案,因为它利用了更广泛的监督来源。

晓的博客 9717

从零开始:使用Verilog在FPGA上实现8051微控制器的完整指南

8051微控制器是一种8位微控制器,由Intel在1980年代初推出。它包括一个CPU、一些RAM和ROM、I/O端口、定时器和串行通信接口。由于其简单的架构和强大的功能,8051已经成为了嵌入式系统设计的首选。FPGA是一种集成电路,设计师可以按照自己的需求进行编程。与传统的ASIC(应用特定集成电路)相比,FPGA提供了更高的灵活性,允许在硬件级别进行快速原型设计和迭代。这里,我们定义了一些基本的输入/输出端口,如时钟clk、复位reset、数据输入/输出和地址输入/输出。

qq_38334677的博客 1331

JavaScript:递归遍历树

The ability to traverse a tree is an important basic foundational concept. A tree is a data structure with a collection of nodes with a hierarchical pattern. Each node is its own data structure. A tre...

weixin_26750481的博客 1423

开发具有情感分析能力的AI Agent

本文将深入探讨开发具有情感分析能力的AI Agent的各个方面。我们将首先介绍情感分析的基础知识,包括定义、背景和应用领域。接着,我们将详细讲解情感分析的核心概念、数据处理方法和算法原理。随后,文章将展示如何设计情感分析系统架构,并进行项目实战,包括环境安装、源代码实现和案例分析。最后,我们将总结最佳实践和注意事项,为读者提供进一步学习的资源。情感分析(Sentiment Analysis),也称为意见挖掘,是自然语言处理(NLP)的一个分支。

SuperAGI2025 1146

JavaScript 树遍历与操作微库——Arboreal

JavaScript 树遍历与操作微库——Arboreal 1. 项目基础介绍 Arboreal 是一个用 JavaScript 编写的开源项目,旨在提供树状数据结构的遍历和操作功能。它适用于 Node.js 环境和浏览器环境,可以帮助开发者轻松地处理树形数据,如组织结构、文件系统目录等。 2. 项目核心功能 Arboreal 的核心功能包括: 树状结构创建与扩展:允许开发者从零开始创建一个树结...

gitblog_00505的博客 357

simulink的Sine Wave 模块详解

模块是 Simulink 中的一个信号源模块,用于生成正弦波信号。该模块可以根据设定的幅值、频率、相位和偏移量,在仿真过程中产生周期性的正弦波形。模块都能提供强有力的支持。通过深入了解其参数的影响及结合 MATLAB 脚本的应用,读者可以更加有效地利用这一模块进行仿真和研究。此外,通过实际应用场景的扩展以及常见问题解答部分的帮助,能够更好地掌握。模块是一个非常实用的工具,适用于需要生成正弦波信号的各种场景。模块的参数,可以进一步增强学习体验。模块参数的影响,下面我们将详细探讨每个参数如何影响仿真结果。

xiaoheshang_123的博客 1052

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

html递归遍历,js中如何递归遍历dom树

本文教程操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。dom树是什么?dom是文档对象模型,为文档提供了结构化表示,并定义了如何通过脚本来访问文档结构。dom是由节点组成的,HTML加载完毕,渲染引擎会在内存中把HTML文档,生成一个DOM树。使用递归遍历dom树:判断传入的数据是否是数组,遍历跟节点functiongetTree2(data,id){//...

weixin_33632843的博客 352

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

JS树的遍历:广度优先遍历与深度优先遍历

JS树的遍历:广度优先遍历与深度优先遍历 先定义一颗简单的树: let tree = [ { label:'a', children:[ { label:'b', children:[ { label:'d' },

九日的博客 4056

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

js遍历节点树

  遍历节点树,节点树如下: &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;遍历节点树&lt;/title&gt; &lt;meta charset="utf-8"/&gt; &lt;/head&gt; &lt;body&gt;

二流码农的博客 4674

JavaScript 处理树 列表转树 遍历树 查找树

树的操作在前端的工作中占据了比较重要的位置,我总结了一些我平时处理树数据的方法 情况一 将列表转换成 tree 有的时候后端比较懒,不愿意处理树数据,给的是一个列表数据,这时候就需要前端将列表转换成 tree 数据 // 列表数据 const list = [ { id: 01, pid: null }, { id: 02, pid: null }, { id: 03, pid: 01 }, { id: 04, pid: 03 }, { id: 05, pid: 01 }, { id

weixin_50964668的博客 784

JavaScript中的树遍历

A tree is a non-linear data structure — a collection of nodes connected by directed (or undirected) edges. Each node contains a value and the connection between nodes is called edges. The top-most nod...

weixin_26750481的博客 532

JS遍历DOM树

遍历页面中的DOM树,输出所有标签 var root=document.documentElement; function forDOM(root) { console.log(root.nodeName); var children=root.children; forChild(children); } function...

LY 1716

js遍历dom树

分享一个简单的js遍历dom树的方法: const DOM_LIST = { node: [], // 默认遍历整个dom树,也可以传递指定dom作为根节点遍历 ergodicDOM(DOM = document.documentElement) { const children = DOM.children; children.length &&a

Limcong_1999的博客 323

通过JavaScript遍历树

Trees are basically just fancy linked lists and creating and deleting nodes on a tree is incredibly simple. Searching on the other hand is a bit more tricky when they’re unsorted, so we’re going to lo...

1470

JavaScript递归遍历树

JavaScript递归遍历树

SuperCustomer的专栏 5676

原生js遍历DOM树

var list = []; //声明一个数组list,用来存放元素的后代元素. function getChildrens(ele){ var children = ele.children; for(var i = 0 ; i &amp;lt; children.length; i++){ var child = children[i]; //c...

Pima 3687

树的遍历--递归思想(JavaScript)

树的遍历--递归思想(JavaScript)

qq_43645678的博客 795
上一篇: 每行程序都有Bug
下一篇: js tab小程序
phangle2015
博客等级 码龄12年 22粉丝 40原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值