diff --git a/Sample.java b/Sample.java index f5c45b5f..f98fb9d5 100644 --- a/Sample.java +++ b/Sample.java @@ -4,4 +4,33 @@ // Any problem you faced while coding this : -// Your code here along with comments explaining your approach \ No newline at end of file +// Your code here along with comments explaining your approach + +public class Sample { + // Time Complexity : O(n) + // Space Complexity : O(h) + // Did this code successfully run on Leetcode : yes + List> ans = new ArrayList<>(); + public List> pathSum(TreeNode root, int targetSum) { + int currSum = 0; + + helper(root, currSum, new ArrayList<>(), targetSum); + return ans; + } + + public void helper(TreeNode root, int currSum, List list, int tar) { + if (root == null) return; + currSum = currSum + root.val; + System.out.println(root.val + " " + currSum + " " + tar); + + list.add(root.val); + if (root.left == null && root.right == null && tar == currSum) { + ans.add(new ArrayList(list)); + } else { + helper(root.left, currSum, list, tar); + helper(root.right, currSum, list, tar); + } + list.remove(list.size()-1); + } + +} \ No newline at end of file diff --git a/SymmetricTree.java b/SymmetricTree.java new file mode 100644 index 00000000..34f18372 --- /dev/null +++ b/SymmetricTree.java @@ -0,0 +1,17 @@ +public class SymmetricTree { + // Time Complexity : O(n) + // Space Complexity : O(h) + // Did this code successfully run on Leetcode : yes + public boolean isSymmetric(TreeNode root) { + if (root == null) return true; + return helper(root.left, root.right); + } + + private boolean helper(TreeNode leftNode, TreeNode rightNode) { + if (leftNode == null && rightNode == null) return true; + if (leftNode == null || rightNode == null) return false; + if (leftNode.val != rightNode.val) return false; + + return helper(leftNode.left, rightNode.right) && helper(leftNode.right, rightNode.left); + } +} \ No newline at end of file