题目描述:
方法一:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def helper(in_left=0,in_right=len(inorder)): nonlocal pre_idx # if there is no elements to construct subtrees if in_left == in_right: return None # pick up pre_idx element as a root root_val = preorder[pre_idx] root = TreeNode(root_val) # root splits inorder list # into left and right subtrees index = idx_map[root_val] # recursion pre_idx += 1 # build left subtree root.left = helper(in_left, index) # build right subtree root.right = helper(index + 1, in_right) return root # start from first preorder element pre_idx = 0 # build a hashmap value -> its index idx_map = {val:idx for idx, val in enumerate(inorder)} return helper()
另:
class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def helper(i,j): while i<j: root = TreeNode(preorder[0]) del preorder[0] root.left = helper(i,idx_map[root.val]) root.right = helper(idx_map[root.val]+1,j) return root idx_map = {val:idx for idx, val in enumerate(inorder)} return helper(0,len(inorder))
原文地址:https://www.cnblogs.com/oldby/p/11184886.html
时间: 2024-11-13 07:57:06