java数据结构普通树的插入方法
时间: 2023-07-06 10:41:09 浏览: 68
在普通树中,每个节点可以有多个子节点,因此插入节点的方式与二叉树不同。下面是一个简单的 Java 代码示例,演示如何向普通树中插入一个新节点:
```
class TreeNode {
int val;
List<TreeNode> children;
public TreeNode(int val) {
this.val = val;
children = new ArrayList<>();
}
public void addChild(TreeNode child) {
children.add(child);
}
public List<TreeNode> getChildren() {
return children;
}
public int getVal() {
return val;
}
}
class Tree {
TreeNode root;
public Tree(int val) {
root = new TreeNode(val);
}
public void insert(int parentVal, int val) {
TreeNode parent = findNode(root, parentVal);
parent.addChild(new TreeNode(val));
}
private TreeNode findNode(TreeNode node, int val) {
if (node.getVal() == val) {
return node;
}
for (TreeNode child : node.getChildren()) {
TreeNode found = findNode(child, val);
if (found != null) {
return found;
}
}
return null;
}
}
```
在上面的代码中,`TreeNode` 类表示普通树的节点,每个节点包含一个值和一个子节点列表。`Tree` 类表示整个普通树,它包括一个根节点,并提供插入节点的方法 `insert`。`findNode` 方法用于在树中查找一个节点,根据节点值递归遍历树,直到找到对应的节点。
使用示例:
```
Tree tree = new Tree(1);
tree.insert(1, 2);
tree.insert(1, 3);
tree.insert(2, 4);
tree.insert(2, 5);
```
上面的代码创建了一个普通树,根节点是 1,1 的子节点是 2 和 3,2 的子节点是 4 和 5。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)