Skip to content

二叉树遍历迭代法

前序遍历

js
var preorderTraversal = function (root) {
  const stack = [];
  const res = [];
  while (root || stack.length) {
    if (root) {
      res.push(root.val);
      stack.push(root);
      root = root.left;
    } else {
      const node = stack.pop();
      root = node.right;
    }
  }
  return res;
};
var preorderTraversal = function (root) {
  const stack = [];
  const res = [];
  while (root || stack.length) {
    if (root) {
      res.push(root.val);
      stack.push(root);
      root = root.left;
    } else {
      const node = stack.pop();
      root = node.right;
    }
  }
  return res;
};

中序遍历

js
var inorderTraversal = function (root) {
  const stack = [];
  const res = [];
  while (root || stack.length) {
    if (root) {
      stack.push(root);
      root = root.left;
    } else {
      const node = stack.pop();
      res.push(node.val);
      root = node.right;
    }
  }
  return res;
};
var inorderTraversal = function (root) {
  const stack = [];
  const res = [];
  while (root || stack.length) {
    if (root) {
      stack.push(root);
      root = root.left;
    } else {
      const node = stack.pop();
      res.push(node.val);
      root = node.right;
    }
  }
  return res;
};

后序遍历

js
var postorderTraversal = function (root) {
  if (!root) return [];
  const stack = [root];
  const res = [];
  while (stack.length) {
    const node = stack.pop();
    res.unshift(node.val);
    node.left && stack.push(node.left);
    node.right && stack.push(node.right);
  }
  return res;
};
var postorderTraversal = function (root) {
  if (!root) return [];
  const stack = [root];
  const res = [];
  while (stack.length) {
    const node = stack.pop();
    res.unshift(node.val);
    node.left && stack.push(node.left);
    node.right && stack.push(node.right);
  }
  return res;
};