How to display flat data structure into hierarchical data structure (Java)?

前端 未结 5 1690
我在风中等你
我在风中等你 2021-02-02 15:11

I have recently faced this question in a practical test for a job .

Suppose you are given a flat data structure like this :

**Category**         **Name**         


        
5条回答
  •  深忆病人
    2021-02-02 15:27

    Here is some sample code that lists them in a hierarchy using recursion. The Item class has a List of children. The trick is adding any new children to the right parent. Here is the method I created to do this:

    public Item getItemWithParent(int parentID){
        Item result = null;
        if(this.categoryID == parentID){
            result = this;
        } else {
            for(Item nextChild : children){
                result = nextChild.getItemWithParent(parentID);
                if(result != null){
                    break;
                }
            }
        }
        return result;
    }
    

    There is probably a more efficient way, but this works.

    Then, when you want to add new items to your hierarchy, do something like this:

    public void addItem(int categoryID, String name, int parentID) {
        Item parentItem = findParent(parentID);
        parentItem.addChild(new Item(categoryID, name, parentID));
    }
    private Item findParent(int parentID) {
        return rootNode.getItemWithParent(parentID);
    }
    

    For the actual display, I just pass in a "tab level" that says how far to tab in, then increment it for each child like this:

    public String toStringHierarchy(int tabLevel){
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < tabLevel; i++){
            builder.append("\t");
        }
        builder.append("-" + name);
        builder.append("\n");
        for(Item nextChild : children){
            builder.append(nextChild.toStringHierarchy(tabLevel + 1));
        }
        return builder.toString();
    }
    

    Which gives me this:

    -electronics
        -Television
            -21inch
                -Test
            -23inch
            -LCD display
        -player
            -mp3player
            -vcd player
                -hd quality
            -dvd player
    

提交回复
热议问题