牛客BM40 重建二叉树
题目:根据中序、前序序列构建二叉树
思想:递归
- 在前序序列的第一个元素为root
- 遍历中序序列,找root的位置
- 将前序、中序序列分隔为左右子树的前序、中序序列
- 递归构造
代码:
public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
if(pre.length == 0 || vin.length == 0) return null;
if(pre.length == 1 && vin.length == 1 && pre[0] == vin[0]) return new TreeNode(pre[0]);
TreeNode root = new TreeNode(pre[0]);
int n = pre.length;
for(int i = 0; i < n; i++) {
if(vin[i] == pre[0]) {
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(vin, 0, i));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i+1, n), Arrays.copyOfRange(vin, i+1, n));
break;
}
}//for
return root;
}//fun
语法要点:按区间复制数组
Arrays.copyOfRange(arr, i, j);//左闭右开