dart-exercism/binary-search-tree/lib/binary_search_tree.dart

46 lines
1.0 KiB
Dart
Raw Normal View History

2024-10-14 11:37:17 +02:00
class BinarySearchTree {
final TreeNode root;
List<String> get sortedData => _traverseInOrder(this.root);
BinarySearchTree(String rootValue) : root = TreeNode(rootValue);
void insert(String value) {
TreeNode newTreeNode = TreeNode(value);
TreeNode currentValue = root;
while (true) {
if (int.parse(value) <= int.parse(currentValue.data)) {
if (currentValue.left == null) {
currentValue.left = newTreeNode;
break;
}
currentValue = currentValue.left!;
} else {
if (currentValue.right == null) {
currentValue.right = newTreeNode;
break;
}
currentValue = currentValue.right!;
}
}
}
List<String> _traverseInOrder(TreeNode? node) {
List<String> data = [];
if (node != null) {
data.addAll(_traverseInOrder(node.left));
data.add(node.data);
data.addAll(_traverseInOrder(node.right));
}
return data;
}
}
class TreeNode {
String data;
TreeNode? left;
TreeNode? right;
TreeNode(this.data);
}