From 9e8fc5e5775b33b240c2848083e60461f8fc7cf2 Mon Sep 17 00:00:00 2001 From: spencerkrebs Date: Sun, 3 May 2026 18:13:10 -0400 Subject: [PATCH] t3 --- pathsum2.py | 29 +++++++++++++++++++++++++++++ symmetric-tree.py | 21 +++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 pathsum2.py create mode 100644 symmetric-tree.py diff --git a/pathsum2.py b/pathsum2.py new file mode 100644 index 00000000..4648b9f9 --- /dev/null +++ b/pathsum2.py @@ -0,0 +1,29 @@ +# O(h) time, O(h) space +# 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,targetSum,currSum,path): + 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: + # We append a copy of the path using list() + # so it doesn't change when we pop later + 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/symmetric-tree.py b/symmetric-tree.py new file mode 100644 index 00000000..ff0f4231 --- /dev/null +++ b/symmetric-tree.py @@ -0,0 +1,21 @@ +# O(n) time bc we visit every node +# O(h) space bc max depth of recursion stack + +# compare the left child of each node to the right child on the other side of the tree + +# 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.ismirror(root.left,root.right) + + def ismirror(self, leftroot, rightroot): + if leftroot and rightroot: + return leftroot.val == rightroot.val and self.ismirror(leftroot.left, rightroot.right) and self.ismirror(leftroot.right,rightroot.left) + return leftroot == rightroot \ No newline at end of file