刷题前最好先看看数据结构:JS数据结构基本操作「中」树与二叉树| 豆包MarsCode AI 刷题

71 阅读2分钟

Hi,这里是正在参加青训营🪖JustHappy,最近不是正好在使用MarsCode AI刷题,正好趁着这个机会再整理一遍在JavaScript中的数据结构的基本操作,争取做到最简单,多一行代码不行、少一行代码不跑那种!这是个人的学习笔记,写的很简单,如果大家想要比较详细的数据结构介绍,推荐去 Hello算法 瞅瞅

javascript-illustration.png

本篇主要记录了“树”、“二叉树”,图画的比较丑,不要介意哦

树 Tree🌲

在咱前端这里,树这个数据结构是一定要掌握的,像DOM Tree、JSON、VDOM这些都会用到相关的知识,所以让我们开始吧🚀

  • JavaScript 中没有树这一数据结构,但是可以用 Object 和 Array 构建树
  • 树是一种分层数据结构

基本的代码结构如下

const tree = {
  val: "a",
  children: [
    {
      val: "b",
      children: [
        {
          val: "d",
          children: [],
        },
        {
          val: "e",
          children: [],
        },
      ],
    },
    {
      val: "c",
      children: [
        {
          val: "f",
          children: [],
        },
        {
          val: "g",
          children: [],
        },
      ],
    },
  ],
};

深度优先遍历

深度优先遍历

  • 尽可能的深的搜索树的分支
算法过程:(这是一个递归)
  1. 访问根节点
  2. 对根节点的 children 挨个进行深度优先遍历
代码如下
const dfs = (root) => {
  console.log(root.val);
  root.children.forEach(dfs);
};

广度优先遍历

  • 先访问和根节点最近的节点
算法过程:
  1. 新建一个队列,将根节点入队
  2. 把队头出队并访问
  3. 把队头的 children 挨个入队
  4. 重复 2、3 步骤,直到队列为空
代码如下
const bfs = (root) => {
  const q = [root];
  while (q.length > 0) {
    const n = q.shift();
    console.log(n.val);
    n.children.forEach((child) => q.push(child));
  }
};

二叉树 Binary Tree

前序遍历

  1. 访问根节点
  2. 对根节点的左子树进行前序遍历
  3. 对根节点的右子树进行前序遍历
  • 递归实现
const preorder = (root) => {
  if (!root) return;
  console.log(root.val);
  preorder(root.left);
  preorder(root.right);
};

  • 非递归实现
const preorder_1 = (root) => {
  if (!root) return;
  const stack = [root];
  while (stack.length) {
    const n = stack.pop();
    console.log(n.val);
    if (n.right) stack.push(n.right);
    if (n.left) stack.push(n.left);
  }
};

中序遍历

  1. 对根节点的左子树进行中序遍历
  2. 访问根节点
  3. 对根节点的右子树进行中序遍历
  • 递归实现
const inorder = (root) => {
  if (!root) return;
  inorder(root.left);
  console.log(root.val);
  inorder(root.right);
};
  • 非递归实现
const inorder_1 = (root) => {
  if (!root) return;
  const stack = [];
  let p = root;
  while (stack.length || p) {
    while (p) {
      stack.push(p);
      p = p.left;
    }
    const n = stack.pop();
    console.log(n.val);
    p = n.right;
  }
};

后序遍历

  1. 对根节点的左子树进行后序遍历
  2. 对根节点的右子树进行后序遍历
  3. 访问根节点
  • 递归实现
const postorder = (root) => {
  if (!root) return;
  postorder(root.left);
  postorder(root.right);
  console.log(root.val);
};
  • 非递归实现
const postorder_1 = (root) => {
  if (!root) return;
  const stack = [root];
  const outputStack = [];
  while (stack.length) {
    const n = stack.pop();
    outputStack.push(n);
    if (n.left) stack.push(n.left);
    if (n.right) stack.push(n.right);
  }
  while (outputStack.length) {
    const n = outputStack.pop();
    console.log(n.val);
  }
};

ok!这篇笔记就到这里,下一篇我们来讲讲图和堆