Java 实现二叉搜索树读csv文件
时间: 2023-09-12 13:10:21 浏览: 84
假设csv文件中每行数据格式为:key, value
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BSTReadCSV {
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
String csvFilePath = "/path/to/csv/file.csv";
try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
String line;
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
int key = Integer.parseInt(data[0]);
String value = data[1];
bst.insert(key, value);
}
} catch (IOException e) {
e.printStackTrace();
}
bst.inOrderTraversal();
}
}
class TreeNode {
int key;
String value;
TreeNode left, right;
public TreeNode(int key, String value) {
this.key = key;
this.value = value;
}
}
class BinarySearchTree {
TreeNode root;
public void insert(int key, String value) {
root = insert(root, key, value);
}
private TreeNode insert(TreeNode node, int key, String value) {
if (node == null) {
return new TreeNode(key, value);
}
if (key < node.key) {
node.left = insert(node.left, key, value);
} else if (key > node.key) {
node.right = insert(node.right, key, value);
} else {
node.value = value;
}
return node;
}
public void inOrderTraversal() {
inOrderTraversal(root);
}
private void inOrderTraversal(TreeNode node) {
if (node == null) {
return;
}
inOrderTraversal(node.left);
System.out.println(node.key + ", " + node.value);
inOrderTraversal(node.right);
}
}
```
注意:这里的实现仅适用于key为int类型的情况,如果key为其他类型,则需要进行相应修改。另外,如果csv文件中存在重复的key值,则只会保留最后一个出现的值。
阅读全文