diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..fe4efc67 --- /dev/null +++ b/Problem1.py @@ -0,0 +1,30 @@ +# 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) +# Space Complexity --> O(log n) +class Solution: + def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: + self.result = [] + self.helper(root, targetSum, 0, []) + return self.result + + def helper(self, root, targetSum, currSum, currList): + # base + if root is None: + return + # logic + currSum = currSum + root.val + currList.append(root.val) + if root.left is None and root.right is None: + if currSum==targetSum: + self.result.append(list(currList)) + + self.helper(root.left, targetSum, currSum, currList) + self.helper(root.right, targetSum, currSum, currList) + # backtrack + currList.pop() diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..860495ba --- /dev/null +++ b/Problem2.py @@ -0,0 +1,25 @@ +# 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) where n is the number of nodes in the tree +# Space Complexity --> O(log n) +class Solution: + def isSymmetric(self, root: Optional[TreeNode]) -> bool: + return self.helper(root.left, root.right) + + def helper(self, n1, n2): + # base + if n1 is None and n2 is None: + return True + if (n1 is None and n2 is not None) or (n1 is not None and n2 is None): + return False + if n1.val!=n2.val: + return False + # logic + case1 = self.helper(n1.left, n2.right) + case2 = self.helper(n1.right, n2.left) + return case1 and case2