Skip to content

Instantly share code, notes, and snippets.

@keimoon
Last active August 29, 2015 14:23
Show Gist options
  • Save keimoon/826e34ac8854c7aefc40 to your computer and use it in GitHub Desktop.
Save keimoon/826e34ac8854c7aefc40 to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
public TreeNode invertTree(TreeNode root) {
Injector injector = Injector.create(new InvertTreeModule());
InvertTreeSolver solver = injector.getInstance(InvertTreeSolver.class);
return solver.solve(root);
}
public static class Injector {
public static Injector create(Module module) {
return new Injector(module);
}
private final Module module;
public Injector(Module module) {
this.module = module;
module.configure();
}
public <T> T getInstance(Class<T> type) {
Constructor<?>[] constructors = type.getConstructors();
Constructor<?> firstConstructor = constructors[0];
Parameter[] params = firstConstructor.getParameters();
List<Object> args = new ArrayList<>();
for (Parameter param : params) {
Class bindingType = module.getBinding(param.getType());
try {
args.add(bindingType.newInstance());
} catch (InstantiationException | IllegalAccessException ex) {
return null;
}
}
try {
return (T) firstConstructor.newInstance(args.toArray(new Object[args.size()]));
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
return null;
}
}
}
public abstract static class Module {
private final Map<Class, Class> classMap = new HashMap<>();
public abstract void configure();
protected <T> void bind(Class<T> from, Class<? extends T> to) {
classMap.put(from, to);
}
public Class getBinding(Class from) {
return classMap.get(from);
}
}
public static class InvertTreeModule extends Module {
@Override
public void configure() {
bind(InvertTreeStrategy.class, AwesomeInvertTreeStrategy.class);
}
}
public static class InvertTreeSolver {
private final InvertTreeStrategy strategy;
public InvertTreeSolver(InvertTreeStrategy strategy) {
this.strategy = strategy;
}
public TreeNode solve(TreeNode root) {
return strategy.invertTree(root);
}
}
public static interface InvertTreeStrategy {
public TreeNode invertTree(TreeNode root);
}
public static class AwesomeInvertTreeStrategy implements InvertTreeStrategy {
@Override
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment