Skip to content
js
/* Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */

前序遍历 根->左->右

js
var preorderTraversal = function (root) {
  if (!root) return [];
  while (root) {
    const left = preorderTraversal(root.left);
    const right = preorderTraversal(root.right);
    return [root.val, ...left, ...right];
  }
};

// 迭代
var preorderTraversal = function (root) {
  if (!root) return [];
  const stack = [],
    res = [];
  while (stack.length || root) {
    while (root) {
      res.push(root.val);
      stack.push(root);
      root = root.left;
    }
    root = stack.pop();
    root = root.right;
  }
  return res;
};

中序遍历 左->根->右

js
var inorderTraversal = function (root) {
  if (!root) return [];
  while (root) {
    const left = inorderTraversal(root.left);
    const right = inorderTraversal(root.right);
    return [...left, root.val, ...right];
  }
};

// 迭代
var inorderTraversal = function (root) {
  if (!root) return [];
  const stack = [],
    res = [];
  while (stack.length || root) {
    while (root) {
      stack.push(root);
      root = root.left;
    }
    root = stack.pop();
    res.push(root.val);
    root = root.right;
  }
  return res;
};

后序遍历 左->右->根

js
var postorderTraversal = function (root) {
  if (!root) return [];
  while (root) {
    const left = postorderTraversal(root.left);
    const right = postorderTraversal(root.right);
    return [...left, ...right, root.val];
  }
};

// 迭代
var postorderTraversal = function (root) {
  if (!root) return [];
  const result = [];
  const stack = [];
  let lastVisited = null;
  let current = root;

  while (current || stack.length > 0) {
    // 遍历到最左节点
    while (current) {
      stack.push(current);
      current = current.left;
    }

    const node = stack[stack.length - 1];

    // 如果右子树为空或已被访问,则访问当前节点
    if (!node.right || node.right === lastVisited) {
      result.push(node.val);
      stack.pop();
      lastVisited = node;
    } else {
      // 否则访问右子树
      current = node.right;
    }
  }

  return result;
};

Released under the MIT License.