将
以
这种形式展现出来
思路:定义数据结构NodeTree将NodeTree放进List,然后遍历每个NodeTree,并将每个NodeTree的深度算出来,有多少深度前面就有多少-,然后打印。递归思想:NodeTree的parentId等于0的时候为最低深度直接返回,用for循环查找当前id的parentId在哪里找到打印一个“-”,然后循环递归。
import java.util.*; public class TestRecursion { static List<NodeTree> nodeList = new ArrayList<>(); public static void main(String[] args) { nodeList.add(new NodeTree(1, 0, "aa")); nodeList.add(new NodeTree(2, 1, "bb")); nodeList.add(new NodeTree(3, 1, "cc")); nodeList.add(new NodeTree(4, 3, "dd")); nodeList.add(new NodeTree(5, 4, "ee")); nodeList.add(new NodeTree(6, 5, "ff")); nodeList.add(new NodeTree(7, 0, "gg")); nodeList.add(new NodeTree(8, 7, "hh")); nodeList.add(new NodeTree(9, 7, "ii")); for (NodeTree nodeTree : nodeList) { print(nodeTree.getParentId(),nodeTree.getName()); System.out.println(""); } } static int x = 0; public static void print(int id, String name) { if (id == 0) { System.out.print("-" + name); return; } for (int i = 0; i < nodeList.size(); i++) { if (nodeList.get(i).getId() == id) { System.out.print("-"); print(nodeList.get(i).getParentId(),name); } } } } class NodeTree { private int id; private int parentId; private String name; public NodeTree() { } public NodeTree(int id, int parentId, String name) { this.id = id; this.parentId = parentId; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getParentId() { return parentId; } public void setParentId(int parentId) { this.parentId = parentId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }