lc105 从前序与中序遍历序列构造二叉树
根据一棵树的前序遍历与中序遍历构造二叉树。
/**
* description:从前序与中序遍历序列构造二叉树
* author:sanmu
*
*/
public class Solution105 {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length == 0 || inorder.length ==0){
return null;
}
return process(preorder,inorder);
}
private TreeNode process(int[] preorder, int[] inorder){
if(preorder.length == 0 || inorder.length == 0){
return null;
}
TreeNode treeNode = new TreeNode(preorder[0]);
if(preorder.length == 1 && inorder.length == 1){
return treeNode;
}
int pos = search(inorder,treeNode.val);
treeNode.left = process(Arrays.copyOfRange(preorder,1,pos+1)
,Arrays.copyOfRange(inorder,0,pos));
treeNode.right = process(Arrays.copyOfRange(preorder,pos+1,preorder.length)
,Arrays.copyOfRange(inorder,pos+1,inorder.length));
return treeNode;
}
private int search(int[] array,int value){
for (int i = 0; i < array.length; i++) {
if(array[i] == value){
return i;
}
}
return -1;
}
}
AC截图(虽然AC但时间和空间都不太理想)
本人公众号,里面有很多计算机专业网盘资源哦,快来关注我获取吧