java将树形结构转为list
时间: 2023-10-08 07:06:54 浏览: 229
你可以使用递归的方式来将树形结构转为list。具体来说,你可以先将根节点加入list中,然后递归处理每个子节点,并将它们加入list中。实现代码如下:
```java
public List<TreeNode> flatten(TreeNode root) {
List<TreeNode> result = new ArrayList<>();
flattenHelper(root, result);
return result;
}
private void flattenHelper(TreeNode node, List<TreeNode> result) {
result.add(node);
for (TreeNode child : node.getChildren()) {
flattenHelper(child, result);
}
}
```
这里假设树节点的定义如下:
```java
public class TreeNode {
private int val;
private 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;
}
}
```
如果你希望将树形结构转为list的同时保留节点的层级信息,可以使用一个helper类来记录每个节点的层级:
```java
public class FlattenedTreeNode {
private TreeNode node;
private int level;
public FlattenedTreeNode(TreeNode node, int level) {
this.node = node;
this.level = level;
}
public TreeNode getNode() {
return node;
}
public int getLevel() {
return level;
}
}
public List<FlattenedTreeNode> flatten(TreeNode root) {
List<FlattenedTreeNode> result = new ArrayList<>();
flattenHelper(root, 0, result);
return result;
}
private void flattenHelper(TreeNode node, int level, List<FlattenedTreeNode> result) {
result.add(new FlattenedTreeNode(node, level));
for (TreeNode child : node.getChildren()) {
flattenHelper(child, level + 1, result);
}
}
```
阅读全文