diff --git a/PathSumTwo.java b/PathSumTwo.java new file mode 100644 index 00000000..007e2c21 --- /dev/null +++ b/PathSumTwo.java @@ -0,0 +1,35 @@ +//Time Complexity - O(n) +//Space Complexity - O(h) +class Solution { + List> result = new ArrayList<>(); + public List> pathSum(TreeNode root, int targetSum) + { + //Validate the root + if (root == null) return new ArrayList<>(); + return helper(root, 0, targetSum, new ArrayList<>()); + } + + public List> helper(TreeNode root, int currSum, int targetSum, List path) + { + //base case + if (root == null) return new ArrayList<>(); + + //logic + path.add(root.val); + currSum += root.val; + + if (root.left == null && root.right == null && currSum == targetSum) + { + result.add(new ArrayList(path)); + } + + //recurse + helper(root.left, currSum, targetSum, path); + helper(root.right, currSum, targetSum, path); + + //back track + path.remove(path.size() - 1); + + return result; + } +} \ No newline at end of file diff --git a/SymetricTree.java b/SymetricTree.java new file mode 100644 index 00000000..dea0e200 --- /dev/null +++ b/SymetricTree.java @@ -0,0 +1,24 @@ +//Approach: Using recursion we can check if the left value is not equal to right val, then return else or else the left and right subtrees are symmetric. +//Time Complexity : O(n) +//Space Complexity: O(1) +class SymetricTree { + public boolean isSymmetric(TreeNode root) + { + if(root == null) return false; + return helper(root.left, root.right); + } + + private boolean helper(TreeNode left, TreeNode right) + { + //base condition + if(left == null && right == null) return true; + + //If any of the left or right nodes is null, that means the other part is not null and so not symmetric + if(left == null || right == null) return false; + + //left value when equals to right value then it is considered symetric + if(left.val != right.val) return false; + + return helper(left.left, right.right) && helper(left.right, right.left); + } +} \ No newline at end of file