Traverse to the deepest using Java

前端 未结 2 949
再見小時候
再見小時候 2021-01-06 00:59

I have a data structure like below:

Task(id,name,subTasks[Task])

But the problem is the subTasks can contain Tasks which have another subTa

2条回答
  •  心在旅途
    2021-01-06 01:23

    Use Guava TreeTraverser:

    Task root = ...
    
    /*
     * For example, you have the following tree:
     *
     *          h
     *        / | \
     *       /  e  \
     *      d       g
     *     /|\      |
     *    / | \     f
     *   a  b  c        
     */
    
    TreeTraverser traverser = new TreeTraverser() {
        @Override
        public Iterable children(Task root) {
            return root.subTasks;
        }
    };
    

    Then you can iterate over the tree with for loop in several ways:

    // Iterate in breadth-first order (hdegabcf)
    for (Task task : traverser.breadthFirstTraversal(root)) { ... }
    

    or

    // Iterate in preorder (hdabcegf)
    for (Task task : traverser.preOrderTraversal(root)) { ... }
    

    or

    // Iterate in postorder (abcdefgh)
    for (Task task : traverser.postOrderTraversal(root)) { ... }
    

提交回复
热议问题