Problem
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:
1 | Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] |
Example 2:
1 | Input: preorder = [-1], inorder = [-1] |
Constraints:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder
andinorder
consist of unique values.- Each value of
inorder
also appears inpreorder
. preorder
is guaranteed to be the preorder traversal of the tree.inorder
is guaranteed to be the inorder traversal of the tree.
Analysis
标准的根据前序和中序遍历恢复二叉树题目。前序提供了根节点的位置,中序提供了左右子树的位置。我们先根据前序的第一个元素,找到在中序对应的位置i
,在中序数组中,[iLeft, i]
是左子树的长度,[i + 1, iRight]
是右子树的长度。然后继续递归下去即可。
Solution
无
Code
1 | /** |
Summary
这道题比较简单,有一个基本的模式和套路,只需要找到根节点和区间,就能重构二叉树。这道题目的分享到这里,感谢你的支持!