Data structures 当问题要求返回树时,应返回什么数据结构作为最终实体
因此,我正在研究一个LeetCode问题,从给定的有序和预有序树遍历序列构造一棵树。给定的骨架代码如下所示:Data structures 当问题要求返回树时,应返回什么数据结构作为最终实体,data-structures,tree,Data Structures,Tree,因此,我正在研究一个LeetCode问题,从给定的有序和预有序树遍历序列构造一棵树。给定的骨架代码如下所示: # 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 cla
# 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:
据我所知,我们是否希望在构建树后返回根节点?是的,我们将返回树的根节点(并直接回答LinkedList类型的问题):
以下是LeetCode的官方解决方案,并附有注释:
class Solution:
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: 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, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: 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()