例如,给出:
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树
//前序遍历和中序遍历可唯一地确定一棵二叉树
//中序遍历和后序遍历可唯一地确定一棵二叉树
import java.util.*;
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0||inorder.length==0){
return null;
}
//对于前序遍历,第一个节点就是根节点
int rootVal = preorder[0];
int leftCount = 0;
//该循环是找出根节点在中序遍历中的位置,以划分左子树和右子树
for(leftCount = 0;leftCount < inorder.length;leftCount++){
if(inorder[leftCount]==rootVal){
break;
}
}
TreeNode root = new TreeNode(rootVal);
//Arrays.copyOfRange(arr,fromIndex,endIndex); 将 arr 数组从 fronIndex 位置开始复制到下标是 endIndex 位置,左闭右开
int[] leftpreorder = Arrays.copyOfRange(preorder,1,leftCount+1);
int[] leftinorder = Arrays.copyOfRange(inorder,0,leftCount);
//构建左子树
root.left = buildTree(leftpreorder,leftinorder);
int[] rightpreorder = Arrays.copyOfRange(preorder,leftCount+1,preorder.length);
int[] rightinorder = Arrays.copyOfRange(inorder,leftCount+1,inorder.length);
//构建右子树
root.right = buildTree(rightpreorder,rightinorder);
return root;
}
}