Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二叉树 #35

Open
jinzhepro opened this issue Apr 19, 2023 · 0 comments
Open

二叉树 #35

jinzhepro opened this issue Apr 19, 2023 · 0 comments

Comments

@jinzhepro
Copy link
Owner

jinzhepro commented Apr 19, 2023

父节点、子节点、根节点、兄弟节点、叶子节点

  • A 节点就是 B 节点的父节点,B 节点是 A 节点的子节点
  • B、C、D这三个节点的父节点是同一个节点,所以它们之间互称为兄弟节点
  • 没有父节点的节点叫做根节点
  • 没有子节点的节点叫做叶子节点

220043e683ea33b9912425ef759556ae

高度、深度、层

高度和深度都是从0开始。

50f89510ad1f7570791dd12f4e9adeb4

满二叉树

叶子节点全都在最底层,除了叶子节点之外,每个节点都有左右两个子节点。

微信截图_20230419110244

完全二叉树

叶子节点都在最底下两层,最后一层叶子结点都靠左排列,除了最后一层,其他层的节点个数要达到最大。

14eaa820cb89a17a7303e8847a412330

解析

基于数组的顺序存储法,根节点为1,左子节点为2i,右子节点为2i+1,父节点为Math.floor(i/2),2i>n则i没有左子节点,2i+1>n则i没有右子节点。

08bd43991561ceeb76679fbb77071223

遍历

复杂度O(n)
flowchart-fun

前序遍历

对于树中的任意节点来说,先打印这个节点,然后再打印它的左子树,最后打印它的右子树。

const preOrder = (node)=>{
  if(!node) return
  console.log(node.value) // 访问节点
  preOrder(node.children ? node.children[0] : null) // 递归左树
  preOrder(node.children ? node.children[1] : null) // 递归右数
}
// 1,2,3,4,5,6,7,8,9,10,11

中序遍历

对于树中的任意节点来说,先打印它的左子树,然后再打印这个节点,最后打印它的右子树。

const inOrder = (node)=>{
  if(!node) return
  inOrder(node.children ? node.children[0] : null) // 递归左树
  console.log(node.value) // 访问节点
  inOrder(node.children ? node.children[1] : null) // 递归右数
}
// 4,,3,5,2,6,1,8,7,10,9,11

后序遍历

对于树中的任意节点来说,先打印它的左子树,然后再打印它的右子树,最后打印这个节点。

const postOrder = (node)=>{
  if(!node) return
  postOrder(node.children ? node.children[0] : null) // 递归左树
  postOrder(node.children ? node.children[1] : null) // 递归右数
  console.log(node.value) // 访问节点
}
// 4,5,3,6,2,8,10,11,9,7,1

层级遍历

按照树的层级顺序打印节点

const levelOrder = (node)=>{
  if(!node.value) return
  const nodes = [] // 存储节点
  let length = [] // 临时数组,循环使用
  length.unshift(node) // push根节点
  while (length.length !==0 ){
    const item = length.shift() // 从临时数组中拿出
    nodes.push(item.value) // push节点列表
    const {children} = item // 遍历子节点
    if(children){
      children.forEach(n=>{
        length.push(n) // push临时数组
      })
    }
  }
  console.log(nodes)
  return nodes // 节点列表
}
// [1, 2, 7, 3,  6, 8, 9, 4, 5, 10, 11]
@jinzhepro jinzhepro changed the title 树的遍历 Apr 19, 2023
@jinzhepro jinzhepro changed the title 二叉树 Apr 19, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant