diff --git a/PathSum2.py b/PathSum2.py new file mode 100644 index 00000000..c8e7ae23 --- /dev/null +++ b/PathSum2.py @@ -0,0 +1,36 @@ +# Time Complexity : O(h) +# Space Complexity : O(h) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : If node is leaf and the current sum equals the target, add a copy of the path to the result. +# After recursive calls, pop the last element to restore the path for other branches. + +# 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 pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: + self.result = [] + self.helper(root, targetSum, 0 , []) + return self.result + + def helper(self, root: Optional[TreeNode], targetSum: int, currSum: int, path: List[int]): + if root is None: + return + + currSum += root.val + path.append(root.val) + + if root.left is None and root.right is None: + if currSum == targetSum: + self.result.append(list(path)) + + self.helper(root.left, targetSum, currSum, path) + self.helper(root.right, targetSum, currSum, path) + + path.pop() + + \ No newline at end of file diff --git a/SymmetricTree.py b/SymmetricTree.py new file mode 100644 index 00000000..1091bfd3 --- /dev/null +++ b/SymmetricTree.py @@ -0,0 +1,39 @@ +# Time Complexity : O(n) +# Space Complexity : O(h) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : Compare the left and right subtrees recursively by checking if +# their root values match and their outer and inner children are mirror images of each other. + + +# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool: + if root is None: + return True + + return self.isSymmetricHelper(root.left, root.right) + + def isSymmetricHelper(self, leftNode, rightNode) -> bool: + if (leftNode is None and rightNode is not None) or (leftNode is not None and rightNode is None): + return False + + if leftNode is None and rightNode is None: + return True + + is_outer = self.isSymmetricHelper(leftNode.left, rightNode.right) + is_inner = self.isSymmetricHelper(leftNode.right, rightNode.left) + + if leftNode.val == rightNode.val and is_outer and is_inner: + return True + + return False + + + + \ No newline at end of file