Assignment 1
Assignment 1
Assignment-1
Shreya sharon
VU21CSEN0101733
1) Given the root of a binary tree, flatten the tree into a "linked list":
The "linked list" should use the same TreeNode class where the right child pointer
points to the next node in the list and the left child pointer is always null.
The "linked list" should be in the same order as a pre-order traversal of the binary tree.
Code:-
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def flatten(root):
if not root:
return
def build_tree(values):
if not values:
return None
return root
def print_flattened_tree(root):
current = root
while current:
print(current.val, end=" -> " if current.right else "\n")
current = current.right
import ast
values = ast.literal_eval(input("Enter tree nodes as a list: "))
root = build_tree(values)
flatten(root)
print("Flattened tree:")
print_flattened_tree(root)
Output:-
Q2) Given n non-negative integers representing an elevation map where the
width of each bar is 1, compute how much water it can trap after raining.
Code:-
def trap(height):
if not height:
return 0
return trapped_water
output