Level Order traversal of a generic tree(n-ary tree) in java

前端 未结 2 1598
Happy的楠姐
Happy的楠姐 2020-12-07 06:23

(In case you want to avoid the lengthy explanation, all I am looking for is a level order traversal for a generic-tree(n-ary tree) in java. The code supplied works and needs

2条回答
  •  無奈伤痛
    2020-12-07 06:52

    The following seems to work. For extra credit, iteration can be done with an enhanced for loop, and aborted at any time. You might want to add access modifiers.

    import java.util.*;
    
    class NaryTree {
        final int data;
        final List children;
    
        public NaryTree(int data, NaryTree... children) {
            this.data = data;
            this.children = Arrays.asList(children);
        }
    
        static class InOrderIterator implements Iterator {
            final Queue queue = new LinkedList();
    
            public InOrderIterator(NaryTree tree) {
                queue.add(tree);
            }
    
            @Override
            public boolean hasNext() {
                return !queue.isEmpty();
            }
    
            @Override
            public Integer next() {
                NaryTree node = queue.remove();
                queue.addAll(node.children);
                return node.data;
            }
    
            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        }
    
        Iterable inOrderView = new Iterable() {
            @Override
            public Iterator iterator() {
                return new InOrderIterator(NaryTree.this);
            } 
        };
    }
    

    Test code:

    public class Test {
        public static void main(String[] args) throws Exception {
            NaryTree tree = new NaryTree(100,
                new NaryTree(90, 
                    new NaryTree(20),
                    new NaryTree(30)
                ), new NaryTree(50, 
                    new NaryTree(200),
                    new NaryTree(300)
                ), new NaryTree(70)
            );
            for (int x : tree.inOrderView) {
                System.out.println(x);
            }
        }
    }
    

提交回复
热议问题