Traverse every unique path (from root to leaf) in an arbitrary tree structure

前端 未结 4 1251
执念已碎
执念已碎 2021-01-31 12:18

I have several lists:

A = [\"a0\", \"a1\"]       // the number of lists varies
B = [\"b0\", \"b1\", \"b2\"] // such as the number of elements in a list.
C = [\"c         


        
4条回答
  •  星月不相逢
    2021-01-31 13:13

    Something that I came up with working on printing the words in a TrieTree that can be easily adaptable to other kinds of trees or different needs:

    public void rootToLeaves() {
        HashMap hashMap = new HashMap();
        for(TrieNode trieNode : root.getChildren())
            rootToLeaves(trieNode, hashMap, 0);
    }
    
    private void rootToLeaves( TrieNode trieNode, HashMap hashMap, int heightIndex ) {
        hashMap.put(heightIndex, trieNode);
    
        if( trieNode.isLeaf() )
            printValues(hashMap, heightIndex);
        else
            for( TrieNode childNode : trieNode.getChildren() )
                rootToLeaves( childNode, hashMap, heightIndex + 1 );
    }
    
    private void printValues(HashMap hashMap, int heightIndex) {
        for(int index = 0; index <= heightIndex; index++)
            System.out.print(hashMap.get(index).getValue());
        System.out.println();
    }
    

    This solution does a nice job in terms of memory management (It uses a single HashMap whose size will never exceed the height of the tree) and it offers a lot of flexibility (Just replace printValues with whatever you need).

    NOTE: Knowing the height of the tree in advance will let you use a simple Array instead of a Map.

提交回复
热议问题