KK's blog

每天积累多一些

0%

LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal

LeetCode



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 <= 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.

算法思路:

N/A

注意事项:

  1. 用递归实现,in_order字符串分左右两段子串递归到左右儿子,pre_order字符串每轮递归用pop(0)原地去除首位,再递归到儿子节点
  2. 终止条件为in_order字符串为空

Python代码:

1
2
3
4
5
6
7
8
9
10
11
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if not inorder:
return None
head = preorder.pop(0)
index = inorder.index(head)
left_inorder, right_inorder = inorder[:index], inorder[index + 1:]

root = TreeNode(head)
root.left = self.buildTree(preorder, left_inorder)
root.right = self.buildTree(preorder, right_inorder)
return root

算法分析:

时间复杂度为O(n),空间复杂度O(1)

Free mock interview