输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
前序遍历可确定根节点,中序遍历可确定左右子树,利用此特点
1.在preorder中确定当前根节点root
2.root.left=helper(左子树对应的index区域)
3.root.right=helper(右子树对应的index区域)`
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0||inorder.length==0)return null;
return helper(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
private TreeNode helper(int[]preorder,int pre_start,int pre_end,int[]inorder,int in_start,int in_end){
if(pre_start>pre_end)return null;
TreeNode root=new TreeNode(preorder[pre_start]);
if(pre_start==pre_end)return root;
int root_index=indexOf(inorder,root.val);
root.left=helper(preorder,pre_start+1,pre_start+root_index-in_start,inorder,in_start,root_index-1);
root.right=helper(preorder,pre_start+root_index-in_start+1,pre_end,inorder,root_index+1,in_end);
return root;
}
private int indexOf(int[]array,int a){
for(int i=0;i<array.length;i++){
if(arr[i]==a)return i;
}
return -1;
}
}