105. 🌟Construct Binary Tree from Preorder and Inorder Traversal (M)
https://leetcode.com/problems/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.
Example 1:

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]Example 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
Constraints:
1 <= preorder.length <= 3000inorder.length == preorder.length-3000 <= preorder[i], inorder[i] <= 3000preorderandinorderconsist of unique values.Each value of
inorderalso appears inpreorder.preorderis guaranteed to be the preorder traversal of the tree.inorderis guaranteed to be the inorder traversal of the tree.
Solution:
类似,我们肯定要想办法确定根节点的值,把根节点做出来,然后递归构造左右子树即可。
我们先来回顾一下,前序遍历和中序遍历的结果有什么特点?
前文 二叉树就那几个框架 写过,这样的遍历顺序差异,导致了 preorder 和 inorder 数组中的元素分布有如下特点:
找到根节点是很简单的,前序遍历的第一个值 preorder[0] 就是根节点的值,关键在于如何通过根节点的值,将 preorder 和 postorder 数组划分成两半,构造根节点的左右子树?
换句话说,对于以下代码中的 ? 部分应该填入什么:
对于代码中的 rootVal 和 index 变量,就是下图这种情况:
现在我们来看图做填空题,下面这几个问号处应该填什么:
对于左右子树对应的 inorder 数组的起始索引和终止索引比较容易确定:
对于 preorder 数组呢?如何确定左右数组对应的起始索引和终止索引?
这个可以通过左子树的节点数推导出来,假设左子树的节点数为 leftSize,那么 preorder 数组上的索引情况是这样的:
看着这个图就可以把 preorder 对应的索引写进去了:
至此,整个算法思路就完成了,我们再补一补 base case 即可写出解法代码:
我们的主函数只要调用 build 函数即可,你看着函数这么多参数,解法这么多代码,似乎比我们上面讲的那道题难很多,让人望而生畏,实际上呢,这些参数无非就是控制数组起止位置的,画个图就能解决了。
Last updated
Was this helpful?



