def collapse_polytomies(phylobuddy, threshold, mode='support'):
    """
    Remove nodes if their support value or branch length are below the given threshold
    :param phylobuddy: PhyloBuddy objecct
    :param threshold: Value below which the node will be removed
    :type threshold: float
    :param mode: Choose which value to apply threshold to (either 'support' or 'length')
    :return: The modified PhyloBuddy object
    """
    if mode not in ['support', 'length']:
        raise NameError("Mode must be 'support' or 'length'")
    for tree in phylobuddy.trees:
        tree.encode_bipartitions()
        for node in tree.postorder_node_iter():
            try:
                value = node.label if mode == 'support' else node.edge_length
                if float(value) < threshold:
                    for child in node.child_nodes():
                        child.parent_node = node.parent_node
                    if node.parent_node:
                        node.parent_node.remove_child(node)
                        tree.encode_bipartitions()
            except TypeError:
                continue
    return phylobuddy
