diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..a8325c34 --- /dev/null +++ b/Problem1.java @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Problem1 { + List> result; + List localResult; + public List> pathSum(TreeNode root, int targetSum) { + result = new ArrayList<>(); + localResult = new ArrayList<>(); + helper(root, 0, targetSum, localResult); + return result; + } + + private void helper(TreeNode root, int sum, int targetSum, List localResult ) { + // base case + if(root == null) return; + //logic + localResult.add(root.val); + sum += root.val; + + if(root.left == null && root.right == null && sum == targetSum) { + result.add(new ArrayList<>(localResult)); + } + helper(root.left, sum, targetSum, new ArrayList<>(localResult)); + helper(root.right, sum, targetSum, new ArrayList<>(localResult)); + localResult.remove(localResult.size() -1); + } +} diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 00000000..7bf9d569 --- /dev/null +++ b/Problem2.java @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Problem2 { + boolean flag; + public boolean isSymmetric(TreeNode root) { + if(root == null) return true; + this.flag = true; + helper(root.left, root.right); + return flag; + } + + private void helper(TreeNode left, TreeNode right){ + if(left == null && right == null) return; + if(left == null || right == null){ + flag = false; + return; + } + if(left.val != right.val){ + flag = false; + } + + if(flag) + helper(left.left, right.right); + + if(flag) + helper(left.right, right.left); + } +}