返回

用 JavaScript 遍历二叉树:步步深入,解开树形结构的奥秘

前端

二叉树:树的二进制表达

二叉树是一种常见的树形结构,由若干个节点组成,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树常用于计算机科学中,例如,二叉搜索树是一种高效的数据结构,常用于查找和存储数据。

二叉树遍历:从根节点出发,探索树的结构

二叉树遍历是一种对二叉树中的每个节点进行访问的过程。遍历二叉树有四种常见的方式:前序遍历、中序遍历、后序遍历和层序遍历。这四种遍历方式都有各自的特点和适用场景。

前序遍历:根、左、右

前序遍历是一种从根节点开始,依次访问根节点、左子节点、右子节点的遍历方式。前序遍历是深度优先搜索的一种,它可以很好地反映二叉树的递归结构。

中序遍历:左、根、右

中序遍历是一种先访问左子节点,再访问根节点,最后访问右子节点的遍历方式。中序遍历也是深度优先搜索的一种,它可以很好地反映二叉树的内部结构。

后序遍历:左、右、根

后序遍历是一种先访问左子节点,再访问右子节点,最后访问根节点的遍历方式。后序遍历也是深度优先搜索的一种,它可以很好地反映二叉树的外部结构。

层序遍历:一层一层地访问节点

层序遍历是一种从二叉树的第一层开始,逐层访问所有节点的遍历方式。层序遍历是一种广度优先搜索,它可以很好地反映二叉树的层级结构。

递归实现二叉树遍历

递归是解决树形结构问题的常用方法,二叉树遍历也可以使用递归来实现。递归实现二叉树遍历的思路是:

  1. 访问根节点。
  2. 递归访问左子节点。
  3. 递归访问右子节点。

递归实现二叉树遍历的代码如下:

function preorderTraversal(root) {
  if (root == null) {
    return;
  }
  console.log(root.val);
  preorderTraversal(root.left);
  preorderTraversal(root.right);
}

function inorderTraversal(root) {
  if (root == null) {
    return;
  }
  inorderTraversal(root.left);
  console.log(root.val);
  inorderTraversal(root.right);
}

function postorderTraversal(root) {
  if (root == null) {
    return;
  }
  postorderTraversal(root.left);
  postorderTraversal(root.right);
  console.log(root.val);
}

非递归实现二叉树遍历

二叉树遍历也可以使用非递归的方式来实现。非递归实现二叉树遍历的思路是:

  1. 使用一个栈来存储需要访问的节点。
  2. 将根节点入栈。
  3. 从栈中弹出栈顶节点,并访问该节点。
  4. 将栈顶节点的左子节点入栈。
  5. 将栈顶节点的右子节点入栈。

非递归实现二叉树遍历的代码如下:

function preorderTraversal(root) {
  if (root == null) {
    return;
  }
  const stack = [root];
  while (stack.length > 0) {
    const node = stack.pop();
    console.log(node.val);
    if (node.right != null) {
      stack.push(node.right);
    }
    if (node.left != null) {
      stack.push(node.left);
    }
  }
}

function inorderTraversal(root) {
  if (root == null) {
    return;
  }
  const stack = [];
  let node = root;
  while (stack.length > 0 || node != null) {
    while (node != null) {
      stack.push(node);
      node = node.left;
    }
    node = stack.pop();
    console.log(node.val);
    node = node.right;
  }
}

function postorderTraversal(root) {
  if (root == null) {
    return;
  }
  const stack = [];
  let node = root;
  let lastVisitedNode = null;
  while (stack.length > 0 || node != null) {
    while (node != null) {
      stack.push(node);
      node = node.left;
    }
    node = stack.pop();
    if (node.right == null || node.right == lastVisitedNode) {
      console.log(node.val);
      lastVisitedNode = node;
      node = null;
    } else {
      stack.push(node);
      node = node.right;
    }
  }
}

总结

二叉树遍历是二叉树的基本操作之一,在计算机科学中有着广泛的应用。二叉树遍历的实现方式多种多样,既可以递归实现,也可以非递归实现。不同遍历方式的实现效率和适