diff --git a/path-sum-2.py b/path-sum-2.py new file mode 100644 index 00000000..bf89dc8f --- /dev/null +++ b/path-sum-2.py @@ -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 \ No newline at end of file diff --git a/symmetric-tree.py b/symmetric-tree.py new file mode 100644 index 00000000..f65c8b35 --- /dev/null +++ b/symmetric-tree.py @@ -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) \ No newline at end of file