-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree-sort.js
52 lines (40 loc) · 1.08 KB
/
tree-sort.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class TreeNode {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
function insert(root, key) {
if (!root) {
return new TreeNode(key);
}
if (key < root.key) {
root.left = insert(root.left, key);
} else if (key > root.key) {
root.right = insert(root.right, key);
}
return root;
}
function inorderTraversal(root, result) {
if (root) {
inorderTraversal(root.left, result);
result.push(root.key);
inorderTraversal(root.right, result);
}
}
function treeSort(arr) {
let root = null;
// Constrói a árvore binária de busca
for (let i = 0; i < arr.length; i++) {
root = insert(root, arr[i]);
}
const result = [];
// Realiza a travessia inorder para obter os elementos ordenados
inorderTraversal(root, result);
return result;
}
const unsortedArray = [38, 27, 43, 3, 9, 82, 10];
const sortedArray = treeSort(unsortedArray);
console.log("Array não ordenado:", unsortedArray);
console.log("Array ordenado:", sortedArray);