LeetCode题解:173. 二叉搜索树迭代器,栈,JavaScript,详细注释

332 阅读1分钟

原题链接:173. 二叉搜索树迭代器

解题思路:

  1. 对二叉搜索树进行中序遍历,即可按顺序输出二叉搜索树的每个值。
  2. 我们可以先回顾一下,使用栈辅助进行中序遍历的代码。
var inorderTraversal = function (root) {
  let result = [];
  let stack = [];
  let curr = root;

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

    node = stack.pop();
    curr = node.right;
    result.push(node.val);
  }

  return result;
};
  1. 每次调用next(),相当于执行一次while循环内代码,并返回node.val
  2. while循环的判断条件,即可作为hasNext()的判断方法。
/**
 * @param {TreeNode} root
 */
var BSTIterator = function (root) {
  this.curr = root; // 缓存当前取值的节点
  this.stack = []; // 缓存下一次要取值的节点
};

/**
 * @return {number}
 */
BSTIterator.prototype.next = function () {
  // 遍历的过程中,可能出现curr为空,而stack中有元素,即为遍历到树的最底端。
  // 也可能出现curr有值而stack为空的情况,如遍历到二叉树的根节点。
  while (this.curr) {
    // 不断向左下遍历节点,同时将所有节点入栈
    this.stack.push(this.curr);
    this.curr = this.curr.left;
  }

  // 将栈顶节点取出,读取它的值
  const node = this.stack.pop();
  // 将node的右子节点赋值给curr,保证遍历顺序
  this.curr = node.right;

  // 返回当前节点的值
  return node.val;
};

/**
 * @return {boolean}
 */
BSTIterator.prototype.hasNext = function () {
  // 当栈被清空,且curr为空时,表示迭代结束
  return Boolean(this.stack.length || this.curr);
};