LeetCode Daily Question 29
May 14th 2022
5 月 14 日 每日一题
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.
1 | Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] |
思路
本题使用递归的写法,首先思考递归公式:
- 将 preoder 的局部第一位设为 root(left 区域的第一个 preorder 或 right 区域的第一个 preoder,因此需要一个 prestart 参数)。
- 找到该 preorder element 在 inorder 中的 index。
- 针对该 preorder element 的 left 区域进入子问题(因此需要 instart 和 inEnd 参数)。
- 针对该 preoder element 的 right 区域进入子问题。
第二步思考临界条件:
prestart >= preorder.size() || instart > inend 时返回 nullptr(无 node)
第三步实现代码。
代码
1 | /** |