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']

猜你喜欢

转载自blog.csdn.net/ganyingxie123456/article/details/124801111