diff --git a/BTRightSideView.java b/BTRightSideView.java new file mode 100644 index 00000000..66cc8bcd --- /dev/null +++ b/BTRightSideView.java @@ -0,0 +1,42 @@ +import java.util.*; + +// BFS O(n) time, O(n) space +class Solution { + public List rightSideView(TreeNode root) { + List ans = new ArrayList<>(); + if (root == null) { + return ans; + } + Queue q = new LinkedList<>(); + q.offer(root); + + while (!q.isEmpty()) { + int size = q.size(); + + for (int i = 0; i < size; i++) { + TreeNode curr = q.poll(); + + if (i == size-1) { // this means its last node (righmost) on that level + ans.add(curr.val); + } + + if (curr.left != null) q.offer(curr.left); + if (curr.right != null) q.offer(curr.right); + } + } + return ans; + } +} + +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; + } +} \ No newline at end of file diff --git a/CousinsInBT.java b/CousinsInBT.java new file mode 100644 index 00000000..4ee4f67e --- /dev/null +++ b/CousinsInBT.java @@ -0,0 +1,44 @@ +import java.util.*; + +// BFS O(n) time, O(n) space +class Solution { + public boolean isCousins(TreeNode root, int x, int y) { + Queue q = new LinkedList<>(); + q.offer(root); + + boolean isXPresent = false; + boolean isYPresent = false; + + while (!q.isEmpty()) { + int size = q.size(); + + for (int i = 0; i < size; i++) { + TreeNode curr = q.poll(); + + if (curr.val == x) { + isXPresent = true; + } + if (curr.val == y) { + isYPresent = true; + } + + if (curr.left != null && curr.right != null) { + // they are siblings not cousins + if (curr.left.val == x && curr.right.val == y) return false; + if (curr.left.val == y && curr.right.val == x) return false; + } + + if (curr.left != null) { + q.offer(curr.left); + } + if (curr.right != null) { + q.offer(curr.right); + } + } + // after each level check if both found or just one found + if (isXPresent && isYPresent) return true; + if (isXPresent || isYPresent) return false; + } + return true; + } +} \ No newline at end of file