diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..3bdb8c08 --- /dev/null +++ b/Problem1.py @@ -0,0 +1,38 @@ +#Path Sum II + +# 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 + +# Time complexity -> O(n), going through each element fif the item +# Space complexity -> O(h), depth of the tree both the stack space and the array space +class Solution: + def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: + resultList=[] + pathList = [] + + currentSum = 0 + + if root!= None: + self.helper(root, targetSum, resultList, pathList, currentSum) + + + return resultList + + def helper(self,root, targetSum, resultList, pathList, currentSum): + pathList.append(root.val) + currentSum+=root.val + + if root.left != None: + self.helper(root.left, targetSum, resultList, pathList, currentSum) + + if root.right != None: + self.helper(root.right, targetSum, resultList, pathList, currentSum) + + if root.left == None and root.right == None and currentSum==targetSum: + resultList.append(pathList[:]) + + pathList.pop() \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..c7ea8950 --- /dev/null +++ b/Problem2.py @@ -0,0 +1,40 @@ +# Symmetric Tree + +# Definition for a binary tree node. + +# Time complexity -> On +# Space Complexity -> On (Contains max breadth in the queue) +# Logic -> Place the supposed to be symmetric items in the queue together, opo both together, compare and continue + +from collections import deque + +# Create a queue +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def isSymmetric(self, root: Optional[TreeNode]) -> bool: + q = deque() + + q.append(root.left) + q.append(root.right) + + while len(q) > 0: + leftElemnt = q.popleft() + rightElement = q.popleft() + if leftElemnt == None and rightElement == None: + continue + if leftElemnt == None or rightElement == None: + return False + if leftElemnt.val != rightElement.val: + return False + q.append(leftElemnt.left) + q.append(rightElement.right) + q.append(leftElemnt.right) + q,append(rightElement.left) + + + return True \ No newline at end of file