[검지 Offer] - 두 갈래 트리 재구성 [Java 버전]
5478 단어 알고리즘 설계와 학습
/**
* Created by Joe on 2018/6/6
*/
/**
* Created by Joe on 2018/6/6
*/
public class Main {
public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
// 1,
if (pre.length == 1) {
return new TreeNode(pre[0]);
}
// 1,
if (pre.length > 1) {
// ,
int rootIndex = findIndex(pre[0], in);
TreeNode node = new TreeNode(pre[0]);
//
int leftLength = rootIndex;
int[] preLeft = new int[leftLength];
System.arraycopy(pre, 1, preLeft, 0, leftLength);
int[] inLeft = new int[leftLength];
System.arraycopy(in, 0, inLeft, 0, leftLength);
//
node.left = reConstructBinaryTree(preLeft, inLeft);
//
int rightLength = in.length - 1 - rootIndex;
int[] preRight = new int[rightLength];
System.arraycopy(pre, 1 + leftLength, preRight,0, rightLength);
int[] inRight = new int[rightLength];
System.arraycopy(in, rootIndex + 1, inRight, 0, rightLength);
//
node.right = reConstructBinaryTree(preRight, inRight);
return node;
}
return null;
}
public static void preTravle(TreeNode node) {
if (node != null) {
System.out.print(node.val + ",");
preTravle(node.left);
preTravle(node.right);
}
}
public int findIndex(int val, int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (val == arr[i]) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
TreeNode root = new Main().reConstructBinaryTree(
new int[] {1,2,4,3,5,6},
new int[] {4,2,1,5,3,6}
);
preTravle(root);
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}