Skip to content

Instantly share code, notes, and snippets.

@ahirschberg
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save ahirschberg/3cf097d332158e5a8ed0 to your computer and use it in GitHub Desktop.

Select an option

Save ahirschberg/3cf097d332158e5a8ed0 to your computer and use it in GitHub Desktop.
Recursive algorithm to generate all possible orderings of a list of elements
private static List<List<TreeNode>> permutations(List<TreeNode> a) { // a is a list containing the child elements of a node
if (a.size() == 1) { // base case of recursion, there is only one possible permutation for a one element list
List<List<TreeNode>> res = new LinkedList<List<TreeNode>>();
res.add(a); // add a into the list of permutations (it is the only element)
return res;
} else {
List<List<TreeNode>> result = new LinkedList<List<TreeNode>>(); // we are returning a list of all the possible orderings of nodes, hence the List<List<>>
for (int i = 0; i < a.size(); i++) {
TreeNode locked = a.get(i); // remove element to be added back in later, 'locking' it in place
List<TreeNode> copiedList = new LinkedList<TreeNode>(a);
copiedList.remove(i);
List<List<TreeNode>> copiedListPermutations = permutations(copiedList); // recursively call permutations() on the new list with the locked element omitted
for (List<TreeNode> permutation : copiedListPermutations) {
permutations.add(0, locked); // stick the locked element back into the list
}
result.addAll(copiedListPermutations); // add all permutations found to the overall list
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment