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
35 changes: 35 additions & 0 deletions path-sum-2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Time Complexity: O(n^2) as we are deepcopying the path whenever we reach the target sum.
# Space Complexity: O(n)
# Did this code successfully run on Leetcode : Yes

# 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]]
"""
res=[]
cpath=[]
def helper(root,csum):
if root==None:
return
cpath.append(root.val)
csum+=root.val
if root.left==None and root.right==None:
if csum==targetSum:
res.append(cpath[:])

helper(root.left,csum)
helper(root.right,csum)

cpath.pop(-1)

helper(root,0)
return res
31 changes: 31 additions & 0 deletions symmetric-tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Time Complexity: O(n).
# Space Complexity: O(n) for recursion stack
# Did this code successfully run on Leetcode : Yes

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

def helper(l,r):
if l==None and r==None:
return True
if l==None or r ==None:
return False

if l.val!=r.val:
return False
else:
lres=helper(l.left,r.right)
rres=helper(l.right,r.left)
return lres and rres

return helper(root,root)