JavaScript 树形(Tree)数据结构

157 阅读2分钟

什么是树形结构

用存储了树根节点的列表表示一个树形结构,每个节点的children属性(如果有)是一颗子树,如果没有children属性或者children长度为0,则表示该节点为叶子节点。

let tree = [
  {
    id: '1',
    title: '节点1',
    children: [
      {
        id: '1-1',
        title: '节点1-1'
      },
      {
        id: '1-2',
        title: '节点1-2'
      }
    ]
  },
  {
    id: '2',
    title: '节点2',
    children: [
      {
        id: '2-1',
        title: '节点2-1'
      }
    ]
  }
]

树形结构遍历方法

树结构遍历方法介绍

树结构的常用场景之一就是遍历,而遍历又分为广度优先遍历、深度优先遍历。其中深度优先遍历是可递归的,而广度优先遍历是非递归的,通常用循环来实现。 深度优先遍历又分为先序遍历、后序遍历,二叉树还有中序遍历,实现方法可以是递归,也可以是循环。 广度优先和深度优先的概念很简单,区别如下:

  • 深度优先,访问完一颗子树再去访问后面的子树,而访问子树的时候,先访问根再访问根的子树,称为先序遍历;先访问子树再访问根,称为后序遍历。

  • 广度优先,即访问树结构的第n+1层前必须先访问完第n层

深度优先遍历的递归实现

先序遍历
function treeForeach (tree, func) {
  tree.forEach(data => {
    func(data)
    data.children && treeForeach(data.children, func) // 遍历子树
  })
}
后序遍历
function treeForeach (tree, func) {
  tree.forEach(data => {
    data.children && treeForeach(data.children, func) // 遍历子树
    func(data)
  })
}

广度优先遍历的实现

广度优先的思路是,维护一个队列,队列的初始值为树结构根节点组成的列表,重复执行以下步骤直到队列为空:

  • 取出队列中的第一个元素,进行访问相关操作,然后将其后代元素(如果有)全部追加到队列最后。

下面是代码实现,类似于数组的forEach遍历,我们将数组的访问操作交给调用者自定义,即一个回调函数:

// 广度优先
function treeForeach (tree, func) {
  let node, list = [...tree]
  while (node = list.shift()) {
    func(node)
    node.children && list.push(...node.children)
  }
}

二维树形结构数组扁平化

    // 二维树形结构数组扁平化为一维数组

    function treeToArray(treeNodes) {
        let result = [];
        function traverse(node, pid) {
            // 唯一id
            const uniqueId = 'id-' + new Date().getTime().toString(36) + '-' + Math.random().toString(36).substr(2, 9);
            const newNode = { ...node }
            // delete newNode.labels
           newNode.pid = pid
            newNode.id = uniqueId
            newNode.children = node.labels
            newNode.isParent = !!node.labels
            // newNode.quest_type = node.quest_type || type
            if (newNode.children) {
                newNode.children.forEach((item) =>
                    item.quest_type = node.quest_type
                )
            }
            result.push(newNode)
            if (node.labels) {
                node.labels.forEach((item) =>
                    traverse(item, uniqueId)
                )
            }
        }

        treeNodes.forEach((item) => traverse(item, '0'))

        return result

    }