Как инвертировать двоичное дерево в JavaScript: рекурсивные, итеративные методы и методы DFS

Чтобы инвертировать двоичное дерево в JavaScript, вы можете использовать несколько методов. Вот некоторые из них:

Метод 1: рекурсивный подход

function invertBinaryTree(root) {
  if (root === null) {
    return null;
  }
// Swap the left and right subtrees
  let temp = root.left;
  root.left = root.right;
  root.right = temp;

  // Invert the left and right subtrees recursively
  invertBinaryTree(root.left);
  invertBinaryTree(root.right);

  return root;
}

Метод 2: итеративный подход с использованием очереди

function invertBinaryTree(root) {
  if (root === null) {
    return null;
  }

  const queue = [root];

  while (queue.length) {
    const node = queue.shift();

    // Swap the left and right subtrees
    let temp = node.left;
    node.left = node.right;
    node.right = temp;

    // Add the left and right children to the queue
    if (node.left !== null) {
      queue.push(node.left);
    }
    if (node.right !== null) {
      queue.push(node.right);
    }
  }

  return root;
}

Метод 3. Поиск в глубину (DFS) с использованием стека

function invertBinaryTree(root) {
  if (root === null) {
    return null;
  }

  const stack = [root];

  while (stack.length) {
    const node = stack.pop();

    // Swap the left and right subtrees
    let temp = node.left;
    node.left = node.right;
    node.right = temp;

    // Add the left and right children to the stack
    if (node.left !== null) {
      stack.push(node.left);
    }
    if (node.right !== null) {
      stack.push(node.right);
    }
  }

  return root;
}

Обратите внимание, что предоставленный код предполагает, что у вас есть структура данных двоичного дерева, где каждый узел имеет свойства leftи right.