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
31 changes: 31 additions & 0 deletions construct-binary-tree-from-inorder-and-postorder-traversal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'''
Time Complexity : O(n)
Space Complexity : O(h)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No
'''

class Solution:

def buildTree(self, inorder, postorder):
self.hashmap={}
self.idx = len(inorder)-1

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

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

def helper(self,postorder,start,end):
if start > end:
return None
rootval = postorder[self.idx]
print(rootval)
root_idx = self.hashmap[rootval]
self.idx -= 1

root = TreeNode(rootval)
root.right = self.helper(postorder,root_idx+1,end)
root.left = self.helper(postorder,start,root_idx-1)
return root
39 changes: 39 additions & 0 deletions sum-root-to-leaf-numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'''
Time Complexity : O(n)
Space Complexity : O(h)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No
'''

# 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 __init__(self):
self.total = 0

def helper(self, root, numCount):
if root == None:
return

numCount = numCount * 10 + root.val

if root.left == None and root.right == None:
self.total += numCount

self.helper(root.left, numCount)
self.helper(root.right, numCount)


def sumNumbers(self, root):
if root == None:
return

self.helper(root, 0)

return self.total