5.1 KiB
id, title, challengeType, forumTopicId, dashedName
id | title | challengeType | forumTopicId | dashedName |
---|---|---|---|---|
587d8259367417b2b2512c83 | Інвертування двійкового дерева | 1 | 301704 | invert-a-binary-tree |
--description--
Тут ми створимо функцію інвертування двійкового дерева. На основі поданого двійкового дерева ми хочемо створити нове дерево, що є його дзеркальним відображенням. Запуск серединного обходу інвертованого дерева досліджує вузли у зворотному порядку у порівнянні з серединним обходом вхідного дерева. Для цього напишіть у нашому двійковому дереві метод під назвою invert
. Цей метод повинен інвертувати поточну структуру дерева. В ідеалі ми б хотіли зробити це in-place за лінійний час. Тобто ми відвідуємо кожен вузол лише один раз і змінюємо вхідну структуру дерева без використання додаткової пам’яті. Успіхів!
--hints--
Повинна існувати структура даних BinarySearchTree
.
assert(
(function () {
var test = false;
if (typeof BinarySearchTree !== 'undefined') {
test = new BinarySearchTree();
}
return typeof test == 'object';
})()
);
Двійкове дерево пошуку повинне мати метод під назвою invert
.
assert(
(function () {
var test = false;
if (typeof BinarySearchTree !== 'undefined') {
test = new BinarySearchTree();
} else {
return false;
}
return typeof test.invert == 'function';
})()
);
Метод invert
повинен правильно інвертувати структуру дерева.
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
.
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--
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--
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--
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
}