From 2f007403ed9d2d0cd20cdd21f0b16bbeb435670b Mon Sep 17 00:00:00 2001 From: RITIKA CHAUBE Date: Wed, 8 Jul 2026 01:08:02 -0400 Subject: [PATCH] Completed Tree-3 --- Problem1.py | 37 +++++++++++++++++++++++++++++++++++++ Problem2.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 Problem1.py create mode 100644 Problem2.py diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..6b665965 --- /dev/null +++ b/Problem1.py @@ -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() \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..b3bb1d3f --- /dev/null +++ b/Problem2.py @@ -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) +