Given a BST, find all sequences of nodes starting from root that will essentially give the same binary search tree.
Given a bst, say
3
/ \\
1
public class Solution {
ArrayList> result;
/*Return the children of a node */
ArrayList getChilden(TreeNode parent) {
ArrayList child = new ArrayList();
if(parent.left != null) child.add(parent.left);
if(parent.right != null) child.add(parent.right);
return child;
}
/*Gets all the possible Compinations*/
void getPermutations(ArrayList permutations, LinkedList current) {
if(permutations.size() == 0) {
result.add(current);
return;
}
int length = permutations.size();
for(int i = 0; i < length; i++) {
TreeNode node = permutations.get(i);
permutations.remove(i);
ArrayList newPossibilities = new ArrayList();
newPossibilities.addAll(permutations);
newPossibilities.addAll(getChilden(node));
LinkedList newCur = new LinkedList();
newCur.addAll(current);
newCur.add(node.val);
getPermutations(newPossibilities, newCur);
permutations.add(i,node);
}
}
/*This method returns a array of arrays which will lead to a given BST*/
ArrayList> inputSequencesForBst(TreeNode node) {
result = new ArrayList>();
if(node == null)
return result;
ArrayList permutations = getChilden(node);
LinkedList current = new LinkedList();
current.add(node.val);
getPermutations(permutations, current);
return result;
}
}
My solution. Works perfectly.