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
39 changes: 39 additions & 0 deletions SumRootToLeafNumbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def sumNumbers(self, root):
"""
:type root: Optional[TreeNode]
:rtype: int
"""
if not root:
return 0

self.ans = 0

def helper(root, total):
#if we hit a null node, nothing to process.
if not root:
return

if not root.left and not root.right:
total = (total * 10) + root.val
#We are at the leaf node. Time to add total to the result.
self.ans += total
return

curTotal = (total * 10) + root.val

# Expand our search
helper(root.left, curTotal)
helper(root.right, curTotal)

helper(root, 0)
return self.ans

#TC: O(n)
#SC : O(h)
48 changes: 48 additions & 0 deletions TreeFromPostorderInorder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: Optional[TreeNode]
"""
if not inorder or not postorder:
return None

self.idxMap = dict()

for i in range(len(inorder)):
self.idxMap[inorder[i]] = i

#postorder array. tree root will be the last.
self.treeRootIdx = len(postorder) - 1

def helper(postorder, start, end):
if start > end:
return None

rootVal = postorder[self.treeRootIdx]
self.treeRootIdx -= 1
rootIdx = self.idxMap[rootVal]

root = TreeNode(rootVal)

# Populate right and left children recursively.
# why right? because we are using postorder array
# to determine the next root.
root.right = helper(postorder, rootIdx + 1, end)

root.left = helper(postorder, start, rootIdx - 1)

return root

return helper(postorder, 0 , len(inorder)-1)


#TC : O(n)
#SC : O(n)