diff --git a/Symmetric_tree.java b/Symmetric_tree.java new file mode 100644 index 00000000..0cc87d0b --- /dev/null +++ b/Symmetric_tree.java @@ -0,0 +1,64 @@ +/** + * 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; + * } + * } + */ + // Time Complexity = O(n) + // Space Complexity = O(n) + // using level order traversal - + /* +class Solution { + public boolean isSymmetric(TreeNode root) { + if(root==null) return true; + Queue q = new LinkedList<>(); + q.add(root.left); + q.add(root.right); + while(!q.isEmpty()){ + TreeNode left = q.poll(); + TreeNode right = q.poll(); + if(left==null && right==null) continue; + if(left==null || right== null) return false; + if(left.val!=right.val) return false; + q.add(left.left); + q.add(right.right); + q.add(left.right); + q.add(right.left); + } + return true; + } +} +*/ + // Time Complexity = O(n) + // Space Complexity = O(h) + // using recursion - +class Solution { + 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); + } +} \ No newline at end of file diff --git a/path_sum_2.java b/path_sum_2.java new file mode 100644 index 00000000..113756a2 --- /dev/null +++ b/path_sum_2.java @@ -0,0 +1,39 @@ +/** + * 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 Solution { + List> result; + public List> pathSum(TreeNode root, int targetSum) { + this.result = new ArrayList<>(); + helper(root,targetSum,0,new ArrayList<>()); + return result; + } + private void helper(TreeNode root,int targetSum, int sum, List path){ + if(root==null) return ; + + sum+=root.val; + path.add(root.val); + if(root.left==null && root.right==null){ + if(sum==targetSum){ + result.add(new ArrayList<>(path)); + } + } + helper(root.left,targetSum,sum,path); + helper(root.right,targetSum,sum,path); + + //backtrack + path.remove(path.size()-1); + } +} \ No newline at end of file