同剑指 Offer 07. 重建二叉树
java:
感谢题解 喵喵喵~
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length == 0) return null;
int rootval = preorder[0];
int rootindex = 0;
for(int i = 0; i < inorder.length; i++){
if( inorder[i] == rootval){
rootindex =i;
break;
}
}
TreeNode root = new TreeNode(rootval);
root.left = buildTree(
Arrays.copyOfRange(preorder, 1, rootindex + 1),
Arrays.copyOfRange(inorder, 0, rootindex)
);
root.right = buildTree(
Arrays.copyOfRange(preorder, rootindex + 1,preorder.length),
Arrays.copyOfRange(inorder, rootindex + 1, inorder.length)
);
return root;
}
}
python3:
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if not (preorder and inorder):
return None
root = TreeNode(preorder[0])
midindex = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1 : midindex + 1], inorder[ : midindex])
root.right = self.buildTree(preorder[midindex + 1 : ], inorder[midindex + 1 : ])
return root