diff --git a/constructBinaryTree.py b/constructBinaryTree.py new file mode 100644 index 00000000..9f1d797b --- /dev/null +++ b/constructBinaryTree.py @@ -0,0 +1,36 @@ +# 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: Use recursion with hashmap. +# The last element in postorder is the root of the tree. +# Use a hashmap to find the index of the root in inorder in O(1). +# Split inorder into left and right subtrees using that index. +# Since we traverse postorder from the end, build the right subtree first, +# then the left subtree. +# Recursively construct the tree until the range becomes invalid. + +class Solution: + def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: + idx_map = {} + for i in range(len(inorder)): + idx_map[inorder[i]] = i + + self.post_idx = len(postorder) - 1 + + def helper(left, right): + if left > right: + return None + + root_val = postorder[self.post_idx] + self.post_idx -= 1 + + root = TreeNode(root_val) + mid = idx_map[root_val] + + root.right = helper(mid + 1, right) + root.left = helper(left, mid - 1) + + return root + + return helper(0, len(inorder) - 1) \ No newline at end of file diff --git a/sumRootToLeaf.py b/sumRootToLeaf.py new file mode 100644 index 00000000..15bbb7ff --- /dev/null +++ b/sumRootToLeaf.py @@ -0,0 +1,31 @@ +# Time Complexity : O(n) +# Space Complexity : O(h) h = height of tree +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: Use DFS traversal. +# Carry the current number formed so far while traversing the tree. +# At each node, update num +# When a leaf node is reached, add the formed number to the result. +# Continue traversal for left and right subtrees. + +# 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: + + def helper(r,num): + if r is None: + return + num = num * 10 + r.val + if r.right is None and r.left is None: + self.res += num + helper(r.left,num) + helper(r.right,num) + + self.res = 0 + helper(root,0) + return self.res \ No newline at end of file