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
37 changes: 37 additions & 0 deletions build_with_postorder_inorder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Time Complexity: O(n)
# Space Complexity: O(n)
# Did this code successfully run on Leetcode : Yes

# 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]
"""
hmap={}
self.rootindex=len(postorder)-1
for i in range(len(inorder)):
hmap[inorder[i]]=i

def helper(in_st,in_end):
if (in_st>in_end):
return None

rootval=postorder[self.rootindex]
in_root_idx=hmap[rootval]
root = TreeNode(rootval)
self.rootindex-=1
root.right = helper(in_root_idx+1,in_end)
root.left = helper(in_st,in_root_idx-1)

return root


return helper(0,len(postorder)-1)
30 changes: 30 additions & 0 deletions sum_root_to_leaf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# // Time Complexity : O(n)
# // Space Complexity : O(h) where h is the height of the tree, for recursive stack space
# // Did this code successfully run on Leetcode : Yes

# 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
"""
self.res=0

def helper(root,cur):
if root == None: return
cur=cur*10 + root.val
if root.left==None and root.right==None:
self.res+=cur
return
helper(root.left,cur)
helper(root.right,cur)

helper(root,0)

return self.res