Skip to content
Open

trees-3 #1564

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
36 changes: 36 additions & 0 deletions PathSum2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Time Complexity : O(h)
# Space Complexity : O(h)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : If node is leaf and the current sum equals the target, add a copy of the path to the result.
# After recursive calls, pop the last element to restore the path for other branches.

# 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: Optional[TreeNode], targetSum: int, currSum: int, path: List[int]):
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:
self.result.append(list(path))

self.helper(root.left, targetSum, currSum, path)
self.helper(root.right, targetSum, currSum, path)

path.pop()


39 changes: 39 additions & 0 deletions SymmetricTree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Time Complexity : O(n)
# Space Complexity : O(h)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : Compare the left and right subtrees recursively by checking if
# their root values match and their outer and inner children are mirror images of each other.


# 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.isSymmetricHelper(root.left, root.right)

def isSymmetricHelper(self, leftNode, rightNode) -> bool:
if (leftNode is None and rightNode is not None) or (leftNode is not None and rightNode is None):
return False

if leftNode is None and rightNode is None:
return True

is_outer = self.isSymmetricHelper(leftNode.left, rightNode.right)
is_inner = self.isSymmetricHelper(leftNode.right, rightNode.left)

if leftNode.val == rightNode.val and is_outer and is_inner:
return True

return False