From d37119a07326a6555f0af6361eb7921c91885cca Mon Sep 17 00:00:00 2001 From: prenastro Date: Wed, 8 Jul 2026 03:49:32 -0700 Subject: [PATCH] Completed s30 Trees-3 --- pathsum2.py | 31 +++++++++++++++++++++++++++++++ symmetrictree.py | 18 ++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 pathsum2.py create mode 100644 symmetrictree.py diff --git a/pathsum2.py b/pathsum2.py new file mode 100644 index 00000000..47df420c --- /dev/null +++ b/pathsum2.py @@ -0,0 +1,31 @@ +class Solution: + def pathSum(self, root, targetSum): + + result = [] + + def dfs(node, remaining, path): + if not node: + return + + # choose + path.append(node.val) + remaining -= node.val + + # leaf node + if not node.left and not node.right: + if remaining == 0: + result.append(path[:]) + + # explore + dfs(node.left, remaining, path) + dfs(node.right, remaining, path) + + # backtrack + path.pop() + + dfs(root, targetSum, []) + + return result + +# TC - O(h) h = height of tree because we only append valid path +# SC - O(h) result is O(h) excluding path used for storing temporary paths \ No newline at end of file diff --git a/symmetrictree.py b/symmetrictree.py new file mode 100644 index 00000000..d0452e48 --- /dev/null +++ b/symmetrictree.py @@ -0,0 +1,18 @@ +class Solution: + def isSymmetric(self, root): + if root is None: + return True + return self.helper(root.left, root.right) + + def helper(self, left, right): + if left is None and right is None: + return True + if left is None or right is None: + return False + if left.val != right.val: + return False + + return self.helper(left.left, right.right) and self.helper(left.right, right.left) + +# TC - O(n) +# SC - O(h) where h - height of tree. \ No newline at end of file