Skip to content
Open

Trees-3 #1574

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
30 changes: 30 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# 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

# Time Complexity --> O(n)
# Space Complexity --> O(log n)
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, currList):
# base
if root is None:
return
# logic
currSum = currSum + root.val
currList.append(root.val)
if root.left is None and root.right is None:
if currSum==targetSum:
self.result.append(list(currList))

self.helper(root.left, targetSum, currSum, currList)
self.helper(root.right, targetSum, currSum, currList)
# backtrack
currList.pop()
25 changes: 25 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# 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

# Time Complexity --> O(n) where n is the number of nodes in the tree
# Space Complexity --> O(log n)
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
return self.helper(root.left, root.right)

def helper(self, n1, n2):
# base
if n1 is None and n2 is None:
return True
if (n1 is None and n2 is not None) or (n1 is not None and n2 is None):
return False
if n1.val!=n2.val:
return False
# logic
case1 = self.helper(n1.left, n2.right)
case2 = self.helper(n1.right, n2.left)
return case1 and case2