From f20a475230f8f036710d40a7a9f613c4dc808789 Mon Sep 17 00:00:00 2001 From: Shinjanee Gupta Date: Wed, 25 Feb 2026 17:33:01 -0800 Subject: [PATCH] completed Trees-2 --- constructTree.py | 32 ++++++++++++++++++++++++++++++++ sumRootToLeafNumbers.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 constructTree.py create mode 100644 sumRootToLeafNumbers.py diff --git a/constructTree.py b/constructTree.py new file mode 100644 index 00000000..33a8dbf3 --- /dev/null +++ b/constructTree.py @@ -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) \ No newline at end of file diff --git a/sumRootToLeafNumbers.py b/sumRootToLeafNumbers.py new file mode 100644 index 00000000..4ec03fd7 --- /dev/null +++ b/sumRootToLeafNumbers.py @@ -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) + + \ No newline at end of file