diff --git a/leetcode_106.py b/leetcode_106.py new file mode 100644 index 00000000..2eee0945 --- /dev/null +++ b/leetcode_106.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Sun Mar 15 00:00:00 2026 + +@author: rishigoswamy + + LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal + Link: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ + + Problem: + Given two integer arrays inorder and postorder where inorder is the inorder + traversal of a binary tree and postorder is the postorder traversal of the same tree, + construct and return the binary tree. + + Note: You may assume that duplicates do not exist in the tree. + + Approach: + Use a hashmap for O(1) inorder index lookup and a global index pointer into postorder. + The last element of postorder is always the root. Its position in inorder splits + the tree into left and right subtrees. + Crucially, right subtree must be built before left (postorder is left→right→root, + so traversing from the end gives root→right→left). + + 1️⃣ Build hMap: value → index for O(1) inorder lookup. + 2️⃣ self.idx starts at len(postorder)-1 and decrements with each root picked. + 3️⃣ createTree(left, right) defines the valid inorder window. + 4️⃣ Pick postorder[self.idx] as root, decrement self.idx. + 5️⃣ Recurse RIGHT first on inorder[rootIdx+1 : right], then LEFT on inorder[left : rootIdx-1]. + + // Time Complexity : O(n) + Each node is visited once; hashmap gives O(1) index lookup. + // Space Complexity : O(n) + O(n) for the hashmap + O(h) recursive call stack (h = height of tree). + +""" + +from typing import List, Optional + +# 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]: + self.hMap = {} + for idx, val in enumerate(inorder): + self.hMap[val] = idx + self.idx = len(inorder) - 1 + return self.createTree(postorder, 0, len(postorder) - 1) + + def createTree(self, postorder, left, right): + if left > right: + return None + + root_val = postorder[self.idx] + self.idx -= 1 + root = TreeNode(root_val) + + rootIdx = self.hMap[root_val] + + root.right = self.createTree(postorder, rootIdx + 1, right) + root.left = self.createTree(postorder, left, rootIdx - 1) + + return root + + ''' + def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: + self.hMap = {} + for idx, val in enumerate(inorder): + self.hMap[val] = idx + + return self.createTree(inorder, postorder) + + def createTree(self, inorder, postorder): + root_val = postorder[-1] + root = TreeNode(root_val) + + root_idx = -1 + for item in inorder: + root_idx += 1 + if root_val == item: + break + + leftInorder = inorder[:root_idx] + rightInorder = inorder[root_idx + 1:] + + leftPostorder = postorder[:root_idx] + rightPostorder = postorder[root_idx:len(postorder) - 1] + + root.right = self.createTree(rightInorder, rightPostorder) if rightInorder else None + root.left = self.createTree(leftInorder, leftPostorder) if leftInorder else None + + return root + ''' + + ''' + def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: + if not postorder: + return None + + idx = inorder.index(postorder[len(postorder) - 1]) + root = TreeNode(postorder[-1]) + + root.right = self.buildTree(inorder[idx + 1:], postorder[idx:len(postorder) - 1]) + root.left = self.buildTree(inorder[:idx], postorder[:idx]) + + return root + ''' diff --git a/leetcode_129.py b/leetcode_129.py new file mode 100644 index 00000000..b268dd81 --- /dev/null +++ b/leetcode_129.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Sun Mar 15 00:00:00 2026 + +@author: rishigoswamy + + LeetCode 129: Sum Root to Leaf Numbers + Link: https://leetcode.com/problems/sum-root-to-leaf-numbers/ + + Problem: + You are given the root of a binary tree containing digits from 0 to 9 only. + Each root-to-leaf path in the tree represents a number (e.g. 1→2→3 = 123). + Return the total sum of all root-to-leaf numbers. + + Approach: + BFS (level-order traversal) using a queue of [node, currentValue] pairs. + Propagate the running number down the tree: at each step, currval = parent*10 + child.val. + When a leaf is reached (no left or right child), add currval to totalsum. + + 1️⃣ Initialize queue with [root, root.val]. + 2️⃣ Pop front of queue; push left/right children with updated currval = currval*10 + child.val. + 3️⃣ If node is a leaf, accumulate currval into totalsum. + 4️⃣ Return totalsum when queue is empty. + + // Time Complexity : O(n) + Every node is visited once. + // Space Complexity : O(n) + Queue holds at most O(n) nodes (worst case: last level of a complete binary tree). + +""" + +from typing import Optional + +# 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: + queue = [] + queue.append([root, root.val]) + totalsum = 0 + + while queue: + node, currval = queue.pop(0) + + if node.left: + queue.append([node.left, currval * 10 + node.left.val]) + if node.right: + queue.append([node.right, currval * 10 + node.right.val]) + + if node.left is None and node.right is None: + totalsum += currval + + return totalsum