数据结构 ~ 树

什么是树 - 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)
相关推荐
凌冰_1 小时前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
郝学胜-神的一滴8 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
console.log('npc')13 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
FR02EN7772 天前
[LeetCode] 26、80.删除有序数组中的重复项 题解
数据结构·算法
H.莓飛2 天前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
饮水桶_T2 天前
Python 面向对象(十七)|继承、封装、多态 笔记
数据结构·笔记·算法
风落青芜3 天前
链式二叉树的实现与基本操作
c语言·开发语言·数据结构·算法
wo_jack3 天前
C++ 入门笔记(十八):list 进阶 —— const 迭代器、operator-> 与 clear 的坑
数据结构·c++·面试·stl·list
ashiho3 天前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口