Skip to content
Open

Trees-2 #1582

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
36 changes: 36 additions & 0 deletions constructBinaryTree.py
Original file line number Diff line number Diff line change
@@ -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)
31 changes: 31 additions & 0 deletions sumRootToLeaf.py
Original file line number Diff line number Diff line change
@@ -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