Skip to content
Open

t3 #1578

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
29 changes: 29 additions & 0 deletions pathsum2.py
Original file line number Diff line number Diff line change
@@ -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()
21 changes: 21 additions & 0 deletions symmetric-tree.py
Original file line number Diff line number Diff line change
@@ -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