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
37 changes: 37 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#Problem 113. PATH SUM II
# TIME COMPELXITY: O(H) where H denotes the height of tree
# SPACE COMPLEXITY: O(H) where H denotes the height of tree as we are making recursion stack based on the height of tree (since doing DFS)

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def pathSum(self, root, targetSum):
"""
:type root: Optional[TreeNode]
:type targetSum: int
:rtype: List[List[int]]
"""
self.result=[]
self.helper(root,targetSum,0,[])
return self.result

def helper(self,root,targetSum,currentSum,path):
#base
if root is None:
return

#logic
path.append(root.val)
currentSum+=root.val

if root.left is None and root.right is None and currentSum==targetSum:
self.result.append(list(path))


self.helper(root.left,targetSum,currentSum,path)
self.helper(root.right,targetSum,currentSum,path)
path.pop()
33 changes: 33 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#Problem 101. SYMMETRIC TREE
# TIME COMPELXITY: O(N) as we need to compare each node N
# SPACE COMPLEXITY: O(H) where H denotes the height of the tree as we are doing recursion stack

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSymmetric(self, root):
"""
:type root: Optional[TreeNode]
:rtype: bool
"""
if root is None:
return True

return self.symmetricCheck(root.left,root.right)

def symmetricCheck(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.symmetricCheck(left.left,right.right) and self.symmetricCheck(left.right,right.left)