数据结构 ~ 树

什么是树 - tree

一种分层数据的抽象模型;

如:DOM、级联选择、树形控件,js 中没有树

可以用 Object 构建树:

javascript 复制代码
const tree = {
  val: 'a',
  children: [
    {
      val: 'a-1',
      children: [
        {
          val: 'a-1-1',
          children: []
        }
      ]
    },
    {
      val: 'a-2',
      children: [
        {
          val: 'a-2-1',
          children: []
        }
      ]
    }
  ]
}

深度优先遍历: 尽可能深的搜索树的分支,即 children 递归

实现:

javascript 复制代码
const dfs = root => {
  console.log(root.val) // a a-1 a-1-1 a-2 a-2-1
  root.children.forEach(e => {
    dfs(e)
  })
}
dfs(tree)

广度优先遍历: 先访问离根节点最近的节点

实现:

javascript 复制代码
const bfs = root => {
  const q = [root] // 队列
  while (q.length) {
    const p = q.shift() // 队头出队、删除第一项(返回第一项)
    console.log(p.val) // a a-1 a-2 a-1-1 a-2-1
    p.children.forEach(e => {
      q.push(e)
    })
  }
}
bfs(tree)

二叉树

树中的节点最多只能有两个子节点;

使用 JS 模拟二叉树结构:

javascript 复制代码
const tree = {
  val: 'a',
  left: {
    val: 'a-left',
    left: { val: 'a-left-left', left: null, right: null },
    right: { val: 'a-left-right', left: null, right: null }
  },
  right: {
    val: 'a-right',
    left: { val: 'a-right-left', left: null, right: null },
    right: { val: 'a-right-right', left: null, right: null }
  }
}

先序遍历:

访问根节点、对根节点的左子树先序先序遍历、对根节点的右子树进行先序遍历;

输出顺序:a、a-left、a-left-left、a-left-right、a-right、a-right-left、a-right-right

javascript 复制代码
const preOrder = root => {
  if (!root) return
  console.log(root.val)
  preOrder(root.left)
  preOrder(root.right)
}
preOrder(tree)

中序遍历:

对根节点左子树进行中序遍历、访问根节点、对根节点的右子树进行中序遍历;

输出顺序:a-left-left、a-left、a-left-right、a、a-right-left、a-right、a-right-right

javascript 复制代码
const inOrder = root => {
  if (!root) return
  inOrder(root.left)
  console.log(root.val)
  inOrder(root.right)
}
inOrder(tree)

后序遍历:

根节点左子树进行后序遍历、根节点右子树进行后续遍历、访问根节点

输出顺序:a-left-left、a-left-right、a-left、a-right-left、a-right-right、a-right、a

javascript 复制代码
const postOrder = root => {
  if (!root) return
  inOrder(root.left)
  inOrder(root.right)
  console.log(root.val)
}
inOrder(tree)
相关推荐
GG.WinGel13 小时前
三元组中心问题
java·数据结构·算法·青少年编程·蓝桥杯
程序员清风14 小时前
缓存、索引与数据结构的工程选择
数据结构·spring·缓存
爱吃火鸡面呀15 小时前
Doris 数据划分实战:List 分区、分桶列与桶数选择
数据结构·list
BK贝壳1 天前
亿级用户签到位图选型复盘:用 bool-hybrid-array 扛冷启动打卡,也把它和 Roaring/Redis 的边界测清楚了
数据结构·python·性能优化·numpy
挖井观天1 天前
《Java数据结构》第一讲:顺序表
数据结构
炘爚1 天前
数据结构算法总结
数据结构·python·算法
见叶之秋1 天前
【C++】红与黑的边界:红黑树从插入到自检
数据结构·c++·算法·面试
kiracrimson1 天前
string 容器:从 C 字符串到会自己扩容的类
开发语言·数据结构·c++·stl
CQU_JIAKE1 天前
10.25【A】
数据结构·算法
海清河晏1112 天前
加油站问题
数据结构·算法·leetcode