二叉树的前中后序遍历

本文介绍了如何使用JavaScript实现二叉树的中序遍历、前序遍历和后序遍历,通过实例展示了在`tree`对象上进行这些操作的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * @Description: 
 * @Autor: zhangbing
 * @Date: 2021-09-03 17:17:44
 * @LastEditors: zhangbing
 * @LastEditTime: 2021-09-03 19:17:12
 */

let tree = {
  val: 5,
  left: {
    val: 2,
    left: {
      val: 1,
      left: null,
      right: null
    },
    right: {
      val: 4,
      left: {
        val: 3,
        left: null,
        right: null
      },
      right: null
    }
  },
  right: {
    val: 6,
    left: null,
    right: {
      val: 7,
      left: null,
      right: null
    }
  }
}

function inorder(root) {
  console.log('中序遍历');

  if (!root) return
  let stack = []
  let p = root

  while (stack.length || p) {
    while (p) {
      stack.push(p)
      p = p.left
    }

    let curNode = stack.pop()
    console.log(curNode.val)
    p = curNode.right
  }
}

inorder(tree)


function preorder(root) {
  console.log('前序遍历');
  if (!root) return
  let stack = [root]
  while (stack.length) {
    let curNode = stack.pop()
    console.log(curNode.val)
    if (curNode.right) stack.push(curNode.right)
    if (curNode.left) stack.push(curNode.left)
  }
}

preorder(tree)


function postorder(root) {
  console.log('后序遍历');
  if (!root) return
  let stack = [root]
  let outputStack = []

  while (stack.length) {
    let curNode = stack.pop()
    outputStack.push(curNode)
    if (curNode.left) stack.push(curNode.left)
    if (curNode.right) stack.push(curNode.right)
  }

  while (outputStack.length) {
    console.log(outputStack.pop().val)
  }
}

postorder(tree)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值