题目
具体代码
/**
* 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 != inorder.length || preorder.length == 0 || inorder.length == 0){
return null;
}
TreeNode node = reTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
return node;
}
public TreeNode reTree(int[] preorder,int preStart,int preEnd,int[] inorder,int inStart,int inEnd){
TreeNode root = new TreeNode(preorder[preStart]);
int leftEnd = 0;
for(int i = inStart;i <= inEnd;i++){
if(inorder[i] == preorder[preStart]){
break;
}
leftEnd++;
}
//左子树
if(leftEnd > 0){
int preLeftStart = preStart+1;
int preLeftEnd = preStart + leftEnd;
int inLeftStart = inStart;
int inLeftEnd = inStart+leftEnd-1;
root.left = reTree(preorder,preLeftStart,preLeftEnd,inorder,inLeftStart,inLeftEnd);
}
//右子树
if((preEnd - preStart)-leftEnd > 0){
int preRightStart = preStart+leftEnd+1;
int preRightEnd = preEnd;
int inRightStart = inStart + leftEnd + 1;
int inRightEnd = inEnd;
root.right = reTree(preorder,preRightStart,preRightEnd,inorder,inRightStart,inRightEnd);
}
return root;
}
}