46 lines
1.0 KiB
Dart
46 lines
1.0 KiB
Dart
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);
|
|
}
|