Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions pathsum2.py
Original file line number Diff line number Diff line change
@@ -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
18 changes: 18 additions & 0 deletions symmetrictree.py
Original file line number Diff line number Diff line change
@@ -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.