[leetcode 105][[从前序与中序遍历序列构造二叉树]
- 给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。
示例 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
示例 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
TreeNode treeNode = new TreeNode();
if (preorder == null || inorder == null) {
return null;
}
if (preorder.length == 1 && inorder.length == 1) {
treeNode.val = preorder[0];
return treeNode;
}
int index = 0;
while (index < inorder.length) {
if (inorder[index] == preorder[0]) {
break;
}
index++;
}
int[] inLeftArr = Arrays.copyOfRange(inorder,0 , index);
int[] inRightArr = null;
if (index + 1 < inorder.length) {
inRightArr = Arrays.copyOfRange(inorder, index + 1, inorder.length);
}
int[] preLeftArr = null;
if (inLeftArr.length != 0) {
preLeftArr = Arrays.copyOfRange(preorder, 1, inLeftArr.length + 1);
}
int[] preRightArr = null;
if (inLeftArr.length + 1 < preorder.length) {
preRightArr = Arrays.copyOfRange(preorder, inLeftArr.length + 1, preorder.length);
}
treeNode.val = preorder[0];
treeNode.left = buildTree(preLeftArr, inLeftArr);
treeNode.right = buildTree(preRightArr, inRightArr);
return treeNode;
}
}