Чтобы инвертировать двоичное дерево в JavaScript, вы можете использовать несколько методов. Вот несколько распространенных подходов:
Метод 1: рекурсивное решение
function invertTree(root) {
if (root === null) {
return null;
}
const left = invertTree(root.left);
const right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
Метод 2: итеративное решение с использованием стека
function invertTree(root) {
if (root === null) {
return null;
}
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
const temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left !== null) {
stack.push(node.left);
}
if (node.right !== null) {
stack.push(node.right);
}
}
return root;
}
Метод 3. Поиск в ширину (BFS) с использованием очереди
function invertTree(root) {
if (root === null) {
return null;
}
const queue = [root];
while (queue.length > 0) {
const node = queue.shift();
const temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left !== null) {
queue.push(node.left);
}
if (node.right !== null) {
queue.push(node.right);
}
}
return root;
}