105. Construct Binary Tree from Preorder and Inorder Traversal
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
Constraints:
- 1 <= preorder.length <= 3000
- inorder.length == preorder.length
- -3000 <= preorder[i], inorder[i] <= 3000
- preorder and inorder consist of unique values.
- Each value of inorder also appears in preorder.
- preorder is guaranteed to be the preorder traversal of the tree.
- inorder is guaranteed to be the inorder traversal of the tree.
Example
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
思路
- 先序遍历(中左右)
- 中序遍历(左中右)
所以先序数组的第一个值肯定是根节点,那在中序数组中该值位置前的所有值,都应该属于该节点的左子树,后面的都属于右子树
这样就能得到一个该节点的左子树中序数组,一个该节点的右子树中序数组。
根据左子树中序数组的长度,就能确定左子树先序数组的长度,然后偏移k个位置赋值,右子树先序数组同理
题解
TreeNode root = new TreeNode();
// 找到当前节点值在中序数组中的位置
int index = 0;
for (int cur : inorder) {
index++;
if (preorder[0] == cur)
break;
}
// 没找到就返回
if(index == 0)
return null;
int[] leftPre = new int[index - 1];
int[] leftIn = new int[index - 1];
int[] rightPre = new int[preorder.length - index];
int[] rightIn = new int[preorder.length - index];
for (int i = 0; i < leftPre.length; i++) {
leftPre[i] = preorder[i + 1];
leftIn[i] = inorder[i];
}
for (int i = 0; i < rightPre.length; i++) {
rightPre[i] = preorder[index + i];
rightIn[i] = inorder[index + i];
}
root.val = preorder[0];
root.left = buildTree(leftPre, leftIn);
root.right = buildTree(rightPre, rightIn);
return root;
标签:Binary,Medium,Preorder,preorder,int,index,length,数组,inorder
From: https://www.cnblogs.com/tanhaoo/p/17103544.html