要将平面数据结构显示为分层数据结构,可以使用树形数据结构。在Java中,可以使用以下方法:
class TreeNode {
Object data;
TreeNode parent;
List<TreeNode> children;
public TreeNode(Object data) {
this.data = data;
this.children = new ArrayList<>();
}
public void addChild(TreeNode child) {
child.parent = this;
children.add(child);
}
}
class Tree {
TreeNode root;
public Tree(Object data) {
this.root = new TreeNode(data);
}
public void addNode(Object parentData, Object childData) {
TreeNode parentNode = findNode(parentData);
if (parentNode != null) {
TreeNode childNode = new TreeNode(childData);
parentNode.addChild(childNode);
}
}
public TreeNode findNode(Object data) {
return findNode(root, data);
}
private TreeNode findNode(TreeNode node, Object data) {
if (node.data.equals(data)) {
return node;
}
for (TreeNode child : node.children) {
TreeNode result = findNode(child, data);
if (result != null) {
return result;
}
}
return null;
}
}
public static Tree createTree(Map<Object, Object> flatData, Object rootData) {
Tree tree = new Tree(rootData);
for (Object childData : flatData.keySet()) {
Object parentData = flatData.get(childData);
tree.addNode(parentData, childData);
}
return tree;
}
public static void printTree(TreeNode node, int level) {
for (int i = 0; i< level; i++) {
System.out.print("\t");
}
System.out.println(node.data);
for (TreeNode child : node.children) {
printTree(child, level + 1);
}
}
public static void main(String[] args) {
Map<Object, Object> flatData = new HashMap<>();
flatData.put("A", null);
flatData.put("B", "A");
flatData.put("C", "A");
flatData.put("D", "B");
flatData.put("E", "B");
flatData.put("F", "C");
Tree tree = createTree(flatData, "A");
printTree(tree.root, 0);
}
这样,平面数据结构就会显示为分层数据结构。
领取专属 10元无门槛券
手把手带您无忧上云