diff --git a/path-sum-ii.py b/path-sum-ii.py new file mode 100644 index 00000000..e8d55dcf --- /dev/null +++ b/path-sum-ii.py @@ -0,0 +1,45 @@ +''' +Time Complexity : O(n*h) +Space Complexity : O(n*h) +Did this code successfully run on Leetcode : Yes +Any problem you faced while coding this : No +''' + +# 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 __init__(self): + self.result = [] + + def helper(self, root, currSum, targetSum, path): + # base + if root == None: + return + + #logic + currSum += root.val + path.append(root.val) + #action + if root.left == None and root.right == None: + if currSum == targetSum: + self.result.append(list(path)) + + # recursion + self.helper(root.left, currSum, targetSum, path) + self.helper(root.right, currSum, targetSum, path) + + + #backtracking + path.pop(-1) + + def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: + if root == None: + return self.result + self.helper(root, 0, targetSum, []) + + return self.result + \ No newline at end of file diff --git a/symmetric-tree.py b/symmetric-tree.py new file mode 100644 index 00000000..6dcaba67 --- /dev/null +++ b/symmetric-tree.py @@ -0,0 +1,35 @@ +''' +Time Complexity : O(n) +Space Complexity : O(h) +Did this code successfully run on Leetcode : Yes +Any problem you faced while coding this : No +''' +# 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 __init__(self): + self.flag = True + + def helper(self, left, right): + # base + if left is None and right is None: + return + + if left is None or right is None or left.val != right.val: + self.flag = False + return + + # logic + self.helper(left.left, right.right) + self.helper(left.right, right.left) + + def isSymmetric(self, root: Optional[TreeNode]) -> bool: + + self.helper(root.left, root.right) + + return self.flag + \ No newline at end of file