Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
1.4 kB
27
Indexable
Never
public static Node treeFromCode(Map<Character, List<Boolean>> code) {
            
            Node rootOfTree = new Branch(0, null, null);
            Node n;
            for(char c: code.keySet()) {
                n = rootOfTree;
                
                List<Boolean> bs = code.get(c);
                for (int i=0;i<bs.size();i++) {
                    boolean b = bs.get(i);
                    boolean leafI = i == bs.size()-1;
                    
                    if (b) {
                        if (leafI)  {
                            
                            ((Branch) n).setRight(new Leaf(c, 0));
                        } else if (((Branch) n).getRight() == null) {
                            
                            ((Branch) n).setRight(new Branch(0, null, null));
                        }
                        n = ((Branch) n).getRight();
                        
                    } else {
                        if (leafI) {
                            ((Branch) n).setLeft(new Leaf(c, 0));
                        } else if (((Branch) n).getLeft() == null) {
                            ((Branch) n).setLeft(new Branch(0, null, null));
                        }
                        n = ((Branch) n).getLeft();
                    }
                }
            }
            return rootOfTree;
        }