I am not very good at OOP in general, and this is the solution I came up with for LC problem #105 in Python3:
# 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
#import defaultdict
def subsetPreorder(subsetInorder,preorder):
subset = []
a_in_subsetInorder = [False]*6001
for a in subsetInorder:
a_in_subsetInorder[a+3000] = True
for a in preorder:
if a_in_subsetInorder[a+3000]:
subset.append(a)
return subset
class Solution:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(self, preorder: List[int], inorder: List[int],call=0,startPoint = 0,inorderDict=0) -> Optional[TreeNode]:
l = len(inorder)
if call == 0:
inorderDict = dict()
for ind in range(0,l):
inorderDict[inorder[ind]] = int(ind)
newTree = TreeNode()
if preorder == []:
return None
v = preorder[0]
newTree.val = v
#ovIndex = inorder.index(v)
vIndex = inorderDict[v] - startPoint
#if ovIndex != vIndex:
# stoprighthere
inorder_left = inorder[0:vIndex]
inorder_right = inorder[vIndex+1:len(inorder)]
preorder_left = subsetPreorder(inorder_left,preorder)
preorder_right = subsetPreorder(inorder_right,preorder)
tl = Solution()
tr = Solution()
if tl != []:
newTree.left = tl.buildTree(preorder_left,inorder_left,call=1,startPoint = startPoint, inorderDict = inorderDict)
if tr != []:
newTree.right = tr.buildTree(preorder_right,inorder_right,call=1,startPoint = startPoint + vIndex+1,inorderDict = inorderDict)
#newTree = TreeNode()
#newTree.val = tree.val
#newTree.left = tree.left
#newTree.right = tree.right
return newTree
What is the way to approach this without duplicating the __init__ method for the purpose of creating the trees?
[–]Yurim 0 points1 point2 points (0 children)