Files
freeCodeCamp/curriculum/challenges/ukrainian/10-coding-interview-prep/data-structures/invert-a-binary-tree.md
2024-06-11 19:02:29 +02:00

193 lines
5.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
id: 587d8259367417b2b2512c83
title: Інвертуйте бінарне дерево
challengeType: 1
forumTopicId: 301704
dashedName: invert-a-binary-tree
---
# --description--
У цьому завданні ми створимо функцію, щоб інвертувати бінарне дерево. Вам дано бінарне дерево; потрібно створити дерево, яке є дзеркальним зображенням цього дерева. При запуску серединного обходу на інвертованому дереві вузли досліджуються у зворотному порядку в порівнянні з серединним обходом початкового дерева. Для цього напишіть на нашому бінарному дереві метод під назвою `invert`. Виклик цього методу має інвертувати поточну структуру дерева. В ідеалі ми б хотіли зробити це на місці за лінійний час. Тобто ми відвідуємо кожен вузол лише один раз і змінюємо наявну структуру дерева без використання додаткової пам’яті. Успіхів!
# --hints--
Має існувати структура даних `BinarySearchTree`.
```js
assert(
(function () {
var test = false;
if (typeof BinarySearchTree !== 'undefined') {
test = new BinarySearchTree();
}
return typeof test == 'object';
})()
);
```
Бінарне дерево пошуку повинне мати метод під назвою `invert`.
```js
assert(
(function () {
var test = false;
if (typeof BinarySearchTree !== 'undefined') {
test = new BinarySearchTree();
} else {
return false;
}
return typeof test.invert == 'function';
})()
);
```
Метод `invert` має правильно інвертувати структуру дерева.
```js
assert(
(function () {
var test = false;
if (typeof BinarySearchTree !== 'undefined') {
test = new BinarySearchTree();
} else {
return false;
}
if (typeof test.invert !== 'function') {
return false;
}
test.add(4);
test.add(1);
test.add(7);
test.add(87);
test.add(34);
test.add(45);
test.add(73);
test.add(8);
test.invert();
return test.inorder().join('') == '877345348741';
})()
);
```
Метод має повернути `null` при спробі інвертувати порожнє дерево.
```js
assert(
(function () {
var test = false;
if (typeof BinarySearchTree !== 'undefined') {
test = new BinarySearchTree();
} else {
return false;
}
if (typeof test.invert !== 'function') {
return false;
}
return test.invert() == null;
})()
);
```
# --seed--
## --after-user-code--
```js
BinarySearchTree.prototype = Object.assign(
BinarySearchTree.prototype,
{
add: function(value) {
function searchTree(node) {
if (value < node.value) {
if (node.left == null) {
node.left = new Node(value);
return;
} else if (node.left != null) {
return searchTree(node.left)
};
} else if (value > node.value) {
if (node.right == null) {
node.right = new Node(value);
return;
} else if (node.right != null) {
return searchTree(node.right);
};
} else {
return null;
};
}
var node = this.root;
if (node == null) {
this.root = new Node(value);
return;
} else {
return searchTree(node);
};
},
inorder: function() {
if (this.root == null) {
return null;
} else {
var result = new Array();
function traverseInOrder(node) {
if (node.left != null) {
traverseInOrder(node.left);
};
result.push(node.value);
if (node.right != null) {
traverseInOrder(node.right);
};
}
traverseInOrder(this.root);
return result;
};
}
}
);
```
## --seed-contents--
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// Only change code below this line
// Only change code above this line
}
```
# --solutions--
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// Only change code below this line
this.invert = function(node = this.root) {
if (node) {
const temp = node.left;
node.left = node.right;
node.right = temp;
this.invert(node.left);
this.invert(node.right);
}
return node;
}
// Only change code above this line
}
```