返回

LeetCode 题解:144. 二叉树的前序遍历,用栈,JavaScript 代码,细致解读

前端

前言

在 LeetCode 的算法挑战中,第 144 题“二叉树的前序遍历”是一个经典的问题。为了更好地理解和解决此问题,本文将使用栈和 JavaScript 代码来进行详细的讲解。我们将从前序遍历的概念入手,逐步分析代码逻辑和算法思想,并辅以清晰的注释,帮助您轻松掌握这一算法。

前序遍历的概念

前序遍历是一种遍历二叉树的方法,其顺序为:根节点、左子树、右子树。换句话说,前序遍历会首先访问根节点,然后递归地遍历左子树,最后递归地遍历右子树。

算法思路

为了使用栈来实现二叉树的前序遍历,我们可以采用以下算法思路:

  1. 将根节点压入栈中。
  2. 循环执行以下步骤,直到栈为空:
    • 将栈顶元素弹出,并将其值添加到结果列表中。
    • 将栈顶元素的右子树压入栈中。
    • 将栈顶元素的左子树压入栈中。

JavaScript 代码实现

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = null;
 *     this.right = null;
 */
/**
 * Given the root of a binary tree, return the preorder traversal of its nodes' values.
 * @param {TreeNode} root
 * @return {number[]}
 */
const preorderTraversal = function(root) {
  // Initialize the stack and the result list.
  const stack = [];
  const result = [];

  // Push the root node into the stack.
  stack.push(root);

  // While the stack is not empty, perform the following steps:
  while (stack.length) {
    // Pop the top element from the stack.
    const node = stack.pop();

    // Add the value of the node to the result list.
    result.push(node.val);

    // Push the right child of the node into the stack.
    if (node.right) {
      stack.push(node.right);
    }

    // Push the left child of the node into the stack.
    if (node.left) {
      stack.push(node.left);
    }
  }

  // Return the result list.
  return result;
};

代码注释

// Initialize the stack and the result list.
const stack = [];
const result = [];

// Push the root node into the stack.
stack.push(root);

// While the stack is not empty, perform the following steps:
while (stack.length) {
  // Pop the top element from the stack.
  const node = stack.pop();

  // Add the value of the node to the result list.
  result.push(node.val);

  // Push the right child of the node into the stack.
  if (node.right) {
    stack.push(node.right);
  }

  // Push the left child of the node into the stack.
  if (node.left) {
    stack.push(node.left);
  }
}

// Return the result list.
return result;
  1. 我们首先初始化一个栈和一个结果列表,用于存储遍历过程中遇到的节点。
  2. 将根节点压入栈中,作为遍历的起点。
  3. 进入循环,只要栈不为空,就不断执行以下步骤:
    • 将栈顶元素弹出,并将其值添加到结果列表中。
    • 将栈顶元素的右子树压入栈中。
    • 将栈顶元素的左子树压入栈中。
  4. 当栈为空时,循环结束,遍历完成,返回结果列表。

复杂度分析

  • 时间复杂度:O(n),其中 n 为二叉树的节点数。这是因为我们访问了每个节点一次,并且每个节点的子树也只访问一次。
  • 空间复杂度:O(n),因为我们需要在栈中存储所有节点。

总结

通过使用栈和 JavaScript 代码,我们成功实现了二叉树的前序遍历算法。希望这篇文章对您的学习有所帮助。如果您有任何问题或建议,欢迎在评论区留言。