树、二叉树的遍历

树的遍历

  • 1、树的结构
let tree = {
      val: 1,
      children: [
        {
          val: 2,
          children: [
            {val: 4, children:[]},
            {val: 5, children: []}
          ]
        },
        {
          val: 3,
          children: [
          {val: 6, children:[]},
          {val: 7, children:[]},
          ]
        }
      ]
    }
  • 2、深度优先遍历(递归)
    const fun = (root) => {
      console.log(root.val)
      root.forEach(fun)
    }
  • 3、广度优先遍历(数组模拟队列的使用,右进左出)
1、新建队列,根节点入队
2、把对头出队
3、把对头的children挨个入队
4、重复2、3步,直到队列为空为止
const fun = (root) => {
      let arr = [root]
      while(arr.length){
        const o = arr.shift()
        o.children.forEach(item => {
          console.log(o.val)
          arr.push(item)
        })
      }
    }

二叉树的遍历

  • 1、二叉树的结构
let binaryTree = {
      val: 1,
      left: {
        val: 2,
        left: {val: 4, left: null, right: null},
        right: {val: 5, left: null, right: null}
      },
      right: {
        val: 3,
        left: {val: 6, left: null, right: null},
        right: {val: 7, left: null, right: null}
      }
    }
  • 2、前序遍历(根左右1、2、4、5、3、6、7)
// 递归方式实现
let arr = []
    const fun = (node) => {
      if(node){
        arr.push(node.val)
        fun(node.left)
        fun(node.right)
      }
    }
    fun(binaryTree) 
    console.log(arr)
//栈的方式实现
if(!root){
      return []
    }
    let arr = []
    let stack = [root]
    while(stack.length){
      let o = stack.pop()
      arr.push(o.val)
      o.right && arr.push(o.right)
      o.left && arr.push(o.left)
    }
    console.log(arr)
  • 3、中序遍历(左根右4、2、5、1、6、3、7)
  • 4、后序遍历
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值