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
32 changes: 32 additions & 0 deletions constructTree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Time Complexity : O(n)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : elements to the left and right of root in inorder array are used to form the left and right subtree.

# 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 buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
def tree(left, right):
if left > right:
return None

root_val = postorder.pop()
root = TreeNode(root_val)

root.right = tree(inorder_idx_map[root_val] + 1, right)
root.left = tree(left, inorder_idx_map[root_val] - 1)

return root

inorder_idx_map = {}

for idx, val in enumerate(inorder):
inorder_idx_map[val] = idx

return tree(0, len(postorder) - 1)
33 changes: 33 additions & 0 deletions sumRootToLeafNumbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Time Complexity : O(n)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : On reaching leaf node, return the number formed so far as it is a complete path.
# Return the sum of results from left and right subtrees to get the final answer.

# 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 helper(self, root: Optional[TreeNode], currNum: int) -> int:
if root == None:
return 0

currNum = currNum * 10 + root.val

if root.left is None and root.right is None:
return currNum

left = self.helper(root.left, currNum)
right = self.helper(root.right, currNum)

return left + right


def sumNumbers(self, root: Optional[TreeNode]) -> int:
return self.helper(root, 0)