数据结构 ~ 树

什么是树 - 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)
相关推荐
牢姐与蒯4 小时前
双指针算法
数据结构·算法
Hesionberger4 小时前
LeetCode406:重建身高队列精髓解析
开发语言·数据结构·python·算法·leetcode
不一样的故事1267 小时前
军工行业合规与基础认知
数据结构·经验分享·算法
闪电悠米19 小时前
力扣hot100-56.合并区间-排序详解
数据结构·算法·leetcode·贪心算法·排序算法
yuannl1021 小时前
图的存储方式
数据结构
会编程的小孩1 天前
初识数据类型以及变量定义
数据结构·算法
梅梅绵绵冰1 天前
数据结构-时间复杂度
数据结构·算法
cpp_25011 天前
P6625 [省选联考 2020 B 卷] 卡牌游戏
数据结构·c++·算法·前缀和·贪心·洛谷题解·省选
起予者汝也1 天前
Python 数据结构
开发语言·数据结构·python
Frostnova丶1 天前
(17)LeetCode 41. 缺失的第一个正数
数据结构·算法·leetcode