遍历菜单树,把每个节点的name拼接出路径来。
java如何遍历菜单树? 并且把每个节点的父name拼接起来(fu+zi+zi)
菜单树遍历
root
note1 (root+note1)
cd1 (root+note1+cd1)
cd2 (root+note1+cd2)
note2
cd3 (root+note2+cd3)
cd4 (root+note2+cd4)
note1路径就是(root+note1)
cd1 路径就是(root+note1+cd1)
红色的就是我要的结果?
不好意思,我金豆就剩这么点了
定义一个节点类,包括一个名字属性以及子节点属性,并且子节点的类型也是该节点;有一个遍历方法,该方法遍历到每一个子节点后就把该子节点的名字加到父节点的名字后面
public class TreeNode { public List<TreeNode> childrens; public String val; public TreeNode(String val) { this.val = val; } } public class TreeIterate { public static void main(String[] args) { TreeNode cd1 = new TreeNode("cd1"); TreeNode cd2 = new TreeNode("cd2"); TreeNode cd3 = new TreeNode("cd3"); TreeNode cd4 = new TreeNode("cd4"); TreeNode note1 = new TreeNode("note1"); TreeNode note2 = new TreeNode("note2"); TreeNode root = new TreeNode("root"); List<TreeNode> note1s = new ArrayList<TreeNode>(); note1s.add(cd1); note1s.add(cd2); note1.childrens = note1s; List<TreeNode> note2s = new ArrayList<TreeNode>(); note2s.add(cd3); note2s.add(cd4); note2.childrens = note2s; List<TreeNode> roots = new ArrayList<TreeNode>(); roots.add(note1); roots.add(note2); root.childrens = roots; iterate("", root); } private static void iterate(String rootStr, TreeNode root) { if(root != null) { System.out.println(rootStr + root.val); List<TreeNode> childrens = root.childrens; if (childrens != null) { for (TreeNode treeNode : childrens) { iterate(rootStr + root.val, treeNode); } } } } }
输出:
root
rootnote1
rootnote1cd1
rootnote1cd2
rootnote2
rootnote2cd3
rootnote2cd4