67,513
社区成员
发帖
与我相关
我的任务
分享
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Test {
/**
* @param sources 通过sql查询生成List<TreeNode>对象
*/
public List<List<TreeNode>> test(List<TreeNode> sources) {
List<List<TreeNode>> result = new ArrayList<>();
for (TreeNode treeNode : sources) {
List<TreeNode> nodes = getChildNodes(treeNode);
if (nodes != null && nodes.size() > 0) {
result.add(nodes);
}
}
return result;
}
/**
* 前序遍历树,获得所有子节点
*/
public static List<TreeNode> getChildNodes(TreeNode node) {
if (node == null) {
return null;
}
List<TreeNode> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();// 创建栈
stack.push(node);// 根节点入栈
while (!stack.isEmpty()) {
TreeNode current = stack.pop();// 节点出栈
result.add(current);
List<TreeNode> children = current.getChildrenTreeNode();// 获得节点的所有子节点
if (children == null || children.size() == 0) {
continue;
}
for (TreeNode child : children) {// 当前节点current的所有子节点入栈
if (child != null) {
stack.push(child);
}
}
}
return result;
}
}
class TreeNode {
private int id;
private String text;
private List<TreeNode> childrenTreeNode;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<TreeNode> getChildrenTreeNode() {
return childrenTreeNode;
}
public void setChildrenTreeNode(List<TreeNode> childrenTreeNode) {
this.childrenTreeNode = childrenTreeNode;
}
}