用泛型写一个通用树状图递归方法
时间: 2023-08-19 16:54:30 浏览: 55
好的,这里是一个使用泛型写的通用树状图递归方法的示例代码:
```java
import java.util.ArrayList;
import java.util.List;
class TreeNode<T> {
private T data;
private List<TreeNode<T>> children;
public TreeNode(T data) {
this.data = data;
this.children = new ArrayList<>();
}
public void addChild(TreeNode<T> child) {
children.add(child);
}
public T getData() {
return data;
}
public List<TreeNode<T>> getChildren() {
return children;
}
}
public class TreeUtils {
public static <T> void traverseTree(TreeNode<T> root) {
System.out.println(root.getData());
for (TreeNode<T> child : root.getChildren()) {
traverseTree(child);
}
}
public static void main(String[] args) {
TreeNode<String> root = new TreeNode<>("A");
TreeNode<String> nodeB = new TreeNode<>("B");
TreeNode<String> nodeC = new TreeNode<>("C");
TreeNode<String> nodeD = new TreeNode<>("D");
TreeNode<String> nodeE = new TreeNode<>("E");
root.addChild(nodeB);
root.addChild(nodeC);
nodeB.addChild(nodeD);
nodeB.addChild(nodeE);
traverseTree(root);
}
}
```
在这个示例中,我们定义了一个通用的树节点类 `TreeNode<T>`,其中泛型 `T` 表示节点的数据类型。节点类包含了节点的数据以及子节点列表。
然后,我们定义了一个名为 `traverseTree` 的通用方法,它使用递归方式遍历树状图并输出每个节点的数据。在 `main` 方法中,我们创建了一个示例树,并调用 `traverseTree` 方法来遍历并打印树中的所有节点。
请注意,这只是一个简单的示例,你可以根据自己的需求扩展和修改该代码。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)