【劍指Offer】- 重建二叉樹[Java版]
阿新 • • 發佈:2018-12-08
題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
/**
* 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;
}
}