Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -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
34 changes: 34 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -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