1.一个树形结构对象,父子节点包含
public class TreeNode{
    private int id;    private String text;    private List<TreeNode> childrenTreeNode ;}2.通过sql查询生成List<TreeNode>对象3.由于层级不确定,所以打算递归生成为List<List<TreeNode>>这种类似二维数组的结构到前台遍历,要按层级,第一层放第一个List,第二层放第二List,想用递归生成,但写了好久都不对,哪位大神帮帮忙,看看

解决方案 »

  1.   

    泛型错了吧  第一次list 里面的类型  和第二次list里面的类型不一样  我瞎猜的
      

  2.   

    不是类型错了,是递归后,不是按层级来的,有的第三级放到第四季List里面去了
      

  3.   

    我这里正好有类似的代码,稍微改了一下,但是用迭代实现的: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;
        }}
      

  4.   

    你这个贴出来的不行啊,不能按照层级分List,你这个最外层list最多两层啊