数据结构 ~ 树

什么是树 - 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)
相关推荐
琢磨先生David6 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245036 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝6 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA6 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc6 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg16 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA6 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX6 天前
020-C++之unordered容器
数据结构·c++
岛雨QA6 天前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法
AKA__Zas6 天前
初识基本排序
java·数据结构·学习方法·排序