Last active
February 4, 2020 18:18
-
-
Save ahlixinjie/3d31196685d5ead075b1cd1b84c4a1ea to your computer and use it in GitHub Desktop.
构建二叉树
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static <R> R buildTreeByStrings2(Integer[] input, Class<R> clazz) {//R为结点类型 | |
if (input == null || input.length == 0) return null; | |
Method getLeft = null; | |
Method getRight = null; | |
Method setLeft = null; | |
Method setRight = null; | |
try {//一定得有这几个方法 | |
getLeft = clazz.getMethod("getLeft"); | |
getRight = clazz.getMethod("getRight"); | |
setLeft = clazz.getMethod("setLeft",clazz); | |
setRight = clazz.getMethod("setRight",clazz); | |
} catch (Exception e) { | |
System.out.println("没有该方法"); | |
} | |
R root = createNode(clazz, input[0]); | |
try { | |
if (root != null) { | |
Queue<R> queue = new LinkedList<>(); | |
queue.offer(root); | |
int i = 1; | |
while (i < input.length) { | |
R node = queue.poll(); | |
R leftChild = createNode(clazz, input[i++]); | |
setLeft.invoke(node, leftChild); | |
if (i < input.length) | |
setRight.invoke(node, createNode(clazz, input[i++])); | |
if (getLeft.invoke(node) != null) queue.offer((R) getLeft.invoke(node)); | |
if (getRight.invoke(node) != null) queue.offer((R) getRight.invoke(node)); | |
} | |
} | |
} catch (Exception ignored) { | |
} | |
return root; | |
} | |
private static <R> R createNode(Class<R> clazz, Integer val) { | |
R node = null; | |
try { | |
Constructor<R> constructor = clazz.getConstructor(int.class); | |
node = constructor.newInstance(val); | |
} catch (Exception ignored) { | |
} | |
return node; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment