diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..ad39346a --- /dev/null +++ b/Problem1.py @@ -0,0 +1,33 @@ +# Construct Binary Tree from Inorder and Postorder Traversal + +# 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: + rootIndex = 0 + def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: + self.rootIndex = len(postorder)-1 + inOrderIndexMap = {} + + for i in range(0,len(inorder)): + inOrderIndexMap[i] = inOrderIndexMap[i] + + return self.helper(inOrderIndexMap,postorder,0,len(inorder)-1) + + + def helper(self, inOrderIndexMap, postorder, inOrderLeftIndex, inorderRightIndex): + if inOrderLeftIndex>inorderRightIndex: + return None + rootVal = postorder[self.rootIndex] + self.rootIndex-=1 + + inOrderRootValIndex = inOrderIndexMap[rootVal] + rootNode = TreeNode(rootVal) + rootNode.right = self.helper(inOrderIndexMap,postorder,inOrderRootValIndex+1,inorderRightIndex) + + rootNode.left = self.helper(inOrderIndexMap,postorder,inOrderLeftIndex,inOrderRootValIndex-1) + + return rootNode \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..d65cbc48 --- /dev/null +++ b/Problem2.py @@ -0,0 +1,34 @@ +#Sum Root to Leaf Numbers + +#Time complexity -> On -> Iterating throguh each node once +#Space complexity -> Oh ->Stack for the tree depyh +# +# Iterate over the left and right nodes and maintain a current number, on moving to child node multiply the current number +# by 10 and add the root value to the current number. Once at leaf add to the number tot he result + +# 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 sumNumbers(self, root: Optional[TreeNode]) -> int: + result = 0 + currentNumber = 0 + return self.helper(root,currentNumber*10, result) + + + def helper(self,root,currentNumber, result ): + + currentNumber = currentNumber + root.val + + if root.left !=None: + result = self.helper(root.left, currentNumber*10, result) + + if root.right != None: + result = self.helper(root.right, currentNumber*10, result) + + if root.left == None and root.right == None: + result+=currentNumber + return result