iterate through recursive objects

前端 未结 5 1629
孤独总比滥情好
孤独总比滥情好 2021-01-29 14:54

I am trying to iterate through a recursive object but Java has no support for this from what I know.

For example, given the object Item:

pub         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-29 15:32

    If the tree is very deep, use a breath-first search as suggested by Eran. If the tree is very wide, use a depth-first search which could look something like:

    class ItemVisitor { 
        public void accept(Item item) {
            // Do something
            for (Item i : item.getChildren()) {
                this.accept(i);
            }
        }
    }
    

    EDIT:

    For a breath-first search, use a queue and append all the children of the current node onto it.

    public void visitTree(Item head) {
        Queue queue = new PriorityQueue();
        while (queue.size() > 0) {
            Item curr = queue.poll();
            // Do something
            for (Item i : curr.getChildren())
                queue.add(i);
        }
    }
    

提交回复
热议问题