js实现二叉树的前、中、后遍历

一颗比较完整的二叉树结构如下:
在这里插入图片描述
前序遍历结果:a b d e c f g
中序遍历结果:d b e a f c g
后续遍历结果:d e b f g c a

构建一颗二叉树

function NodeTree(value) {
 this.value = value
  this.left = null
  this.right = null
}
let ta = new NodeTree('a'),
  tb = new NodeTree('b'),
  tc = new NodeTree('c'),
  td = new NodeTree('d'),
  te = new NodeTree('e'),
  tf = new NodeTree('f'),
  tg = new NodeTree('g');
ta.left = tb;
ta.right = tc;
tb.left = td;
tb.right = te;
tc.left = tf;
tc.right = tg;

方法一:递归

// 保存遍历的结果
let tF = [], tM = [], tE = []

// 前序
function treeFront(root) {
  if (!root || root.value === null) {
    return null
  }
  tF.push(root.value)
  treeFront(root.left)
  treeFront(root.right)
  return tF
}

// 中序
function treeMiddle(root) {
  if (!root || root.value === null) {
    return null
  }
  treeMiddle(root.left)
  tM.push(root.value)
  treeMiddle(root.right)
  return tM
}

// 后序
function treeEnd(root) {
  if (!root || root.value === null) {
    return null
  }
  treeEnd(root.left)
  treeEnd(root.right)
  tE.push(root.value)
  return tE
}

// test
console.log("前序: ", treeFront(ta)); // ['a', 'b', 'd', 'e', 'c', 'f', 'g']
console.log("中序: ", treeMiddle(ta)); // ['d', 'b', 'e', 'a', 'f', 'c', 'g']
console.log("后序: ", treeEnd(ta)); // ['d', 'e', 'b', 'f', 'g', 'c', 'a']

方法二:非递归

// 前序
function preorderTraversal(root) {
  const stack = [], result = []
  root && stack.push(root)
  while (stack.length > 0) {
    let curNode = stack.pop()
    if (curNode !== null) {
      result.push(curNode.value)
      curNode && stack.push(curNode.right)
      curNode && stack.push(curNode.left)
    }
  }
  return result
}

// 中序
function inorderTraversal(root) {
  const stack = [], result = []
  let node = root
  while (stack.length > 0 || node !== null) {
    if (node) {
      stack.push(node)
      node = node.left
    } else {
      node = stack.pop()
      result.push(node.value)
      node = node.right
    }
  }
  return result
}

// 后序
function postorderTraversal(root) {
  const stack = [], result = []
  while (root || stack.length) {
    result.unshift(root.value)
    root.left && stack.push(root.left)
    root.right && stack.push(root.right)
    root = stack.pop()
  }
  return result
}

// test
console.log("前序: ", preorderTraversal(ta)); // ['a', 'b', 'd', 'e', 'c', 'f', 'g']
console.log("中序: ", inorderTraversal(ta)); // ['d', 'b', 'e', 'a', 'f', 'c', 'g']
console.log("后序: ", postorderTraversal(ta)); // ['d', 'e', 'b', 'f', 'g', 'c', 'a']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

英子的搬砖日志

您的鼓励是我创作的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值