美文网首页
js-树的遍历

js-树的遍历

作者: 小猪佩奇的王子 | 来源:发表于2019-11-10 10:54 被阅读0次

数据

var tree = [
    {
        name: "A",
        children: [
            {
                name: "B",
                children: [
                    {
                        name: "E"
                    },
                    {
                        name: "F"
                    }
                ]
            },
            {
                name: "C",
                children: [
                    {
                        name: "G"
                    },
                    {
                        name: "H"
                    }
                ]
            },
            {
                name: "D",
                children: [
                    {
                        name: "I"
                    },
                    {
                        name: "J"
                    }
                ]
            }
        ]
    }
]

广度优先遍历

var list = []
function wideSearch(tree) {
    let nodes = []
    nodes = nodes.concat(tree)
    var shift = nodes.shift()
    list.push(shift)
    if (shift.children) {
        nodes = nodes.concat(shift.children)
    }
    if (nodes.length > 0) {
        wideSearch(nodes)
    }
    return nodes
}

深度优先遍历

var list = []
function deepSearch(tree) {
    for (var i = 0; i < tree.length; i++) {
        list.push(tree[i].name)
        if (tree[i].children) {
            deepSearch(tree[i].children)
        }
    }
}

深度优先不递归

function deepSearchStack(tree) {
    var stack = []
    var result = []
    stack = stack.concat(tree)
    while (stack.length > 0) {
        var node = stack.pop()
        result.push(node.name)
        if (node.children) {
            stack = stack.concat(node.children.reverse())
        }
    }
    console.log(result)
}

deepSearchStack(tree)

相关文章

  • js-树的遍历

    数据 广度优先遍历 深度优先遍历 深度优先不递归

  • js-遍历

    一、对数组的遍历 1. for循环 语法结构: var arr =[1,2,3];for(var i=0; i

  • js-对象遍历

    2018年4月24号更新 在写代码的过程中有时可能要对一个对象进行遍历,然后进行相应的操作,那么对象该怎么遍历呢?...

  • js-数组遍历

    数组遍历

  • 树的遍历算法

    树的递归遍历 树的层次遍历 树的非递归前序遍历 树的非递归中序遍历

  • 图的深度优先遍历

    数据结构遍历的意义 树的遍历 图的遍历 树的前序遍历 图遍历和树遍历区别 知识回顾 树的深度优先遍历 普通函数和递...

  • js-数组的遍历

    关于数组的遍历我们可以有很多方法,for循环,forEach方法,map方法等等,定义一个数组arry,各方法的使...

  • 树的遍历

    N叉树的遍历 N叉树的前序遍历 N叉树的后序遍历 N叉树的层序遍历 二叉树 鉴于递归法遍历比较简单,就不重复写了 ...

  • 数据结构与算法之二叉树遍历(七)

    目录 前序遍历中序遍历后序遍历层序遍历遍历方式的选择条件根据遍历结果重构二叉树翻转二叉树计算二叉树的高度判断一棵树...

  • 数据结构——树和森林的遍历方法

    树的遍历 1、树的遍历的定义:以某种方式访问树中的每一个结点,且仅访问一次。 树的遍历主要有先根遍历和后根遍历。2...

网友评论

      本文标题:js-树的遍历

      本文链接:https://www.haomeiwen.com/subject/pgnobctx.html