diff --git a/problem1.py b/problem1.py new file mode 100644 index 00000000..c7f0b20b --- /dev/null +++ b/problem1.py @@ -0,0 +1,34 @@ +# problem 1 + +#https://leetcode.com/problems/binary-search-tree-iterator/ + +# 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 BSTIterator: + + def __init__(self, root: Optional[TreeNode]): + self.arr = [] + self.dfs(root) + + def dfs(self,root): + while(root): + self.arr.append(root) + root = root.left + + def next(self) -> int: + last_node = self.arr.pop() + self.dfs(last_node.right) + return last_node.val + + def hasNext(self) -> bool: + return True if len(self.arr)>0 else False + + +# Your BSTIterator object will be instantiated and called as such: +# obj = BSTIterator(root) +# param_1 = obj.next() +# param_2 = obj.hasNext() \ No newline at end of file diff --git a/problem2.py b/problem2.py new file mode 100644 index 00000000..e17dadc3 --- /dev/null +++ b/problem2.py @@ -0,0 +1,26 @@ +# problem 2 +# https://leetcode.com/problems/reorder-list/ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reorderList(self, head: Optional[ListNode]) -> None: + """ + Do not return anything, modify head in-place instead. + """ + all_path = [] + fwd_head = head + while(fwd_head): + all_path.append(fwd_head) + fwd_head = fwd_head.next + str_idx = 0 + end_idx = len(all_path)-1 + while(str_idx value stored in node + self.data = data + self.next = None + } +''' +class Solution: + def deleteNode(self, del_node): + # code here + if del_node is None or del_node.next is None: + return + + del_node.data = del_node.next.data + del_node.next = del_node.next.next \ No newline at end of file diff --git a/problem4.py b/problem4.py new file mode 100644 index 00000000..3ee9ccc1 --- /dev/null +++ b/problem4.py @@ -0,0 +1,36 @@ +## Problem4 (https://leetcode.com/problems/intersection-of-two-linked-lists/) + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: + length_headA = 0 + length_headB = 0 + startA = headA + while(startA): + length_headA+=1 + startA = startA.next + startB = headB + while(startB): + length_headB+=1 + startB = startB.next + if length_headA > length_headB: + loop_count = length_headA - length_headB + while(loop_count>0): + headA = headA.next + loop_count-=1 + else: + loop_count = length_headB - length_headA + while(loop_count>0): + headB = headB.next + loop_count-=1 + while(headB): + if headA == headB: + return headA + headB= headB.next + headA = headA.next + return headA \ No newline at end of file