Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

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.

Example 1:

1
2
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

Example 2:

1
2
Input: preorder = [-1], inorder = [-1]
Output: [-1]

從前中序結果建出原本的樹,前序可以找root, 中序可以建樹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
T: O(n), S: O(1)
# Definition for a binary tree node.
# class TreeNode:
# def init(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
# pre : (root, left, right) root is first, find root
# in: (left, root, right) construct tree

# Check if the root exist in inorder
if len(preorder) and preorder[0] in inorder:

# Find the root index in inorer
root_index = inorder.index(preorder[0])

# Make the root node
tree = TreeNode(preorder[0])

# Build left subtree
tree.left = self.buildTree(preorder[1:root_index+1], inorder[:root_index])

# Build right subtree
tree.right = self.buildTree(preorder[root_index+1:], inorder[root_index+1:])
return tree

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels