@@ -0,0 +1,2657 @@
+package com.freetymekiyan.algorithms.level.medium;%0A%0Aimport com.freetymekiyan.algorithms.utils.Utils.TreeNode;%0A%0Aimport java.util.ArrayDeque;%0Aimport java.util.ArrayList;%0Aimport java.util.List;%0Aimport java.util.Queue;%0A%0A/**%0A * Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see%0A * ordered from top to bottom.%0A * %3Cp%3E%0A * For example:%0A * Given the following binary tree,%0A * 1            %3C---%0A * /   %5C%0A * 2     3         %3C---%0A * %5C     %5C%0A * 5     4       %3C---%0A * You should return %5B1, 3, 4%5D.%0A * %3Cp%3E%0A * Tags: Tree, Depth-first Search, Breadth-first Search%0A * Similar: Problems (M) Populating Next Right Pointers in Each Node%0A */%0Apublic class BinaryTreeRigthSideView %7B%0A%0A    /**%0A     * BFS.%0A     * Do a level order traversal with queue.%0A     * For each level, traverse each node and add children to the queue.%0A     * If it's at the end of current level, add node's value to result.%0A     * %3Cp%3E%0A     * Easy to understand, but queue.poll() and queue.offer() can be slow.%0A     */%0A    public List%3CInteger%3E rightSideView(TreeNode root) %7B%0A        if (root == null) %7B%0A            return null;%0A        %7D%0A        List%3CInteger%3E res = new ArrayList%3C%3E();%0A        Queue%3CTreeNode%3E queue = new ArrayDeque%3C%3E();%0A        queue.offer(root);%0A        while (!queue.isEmpty()) %7B%0A            int size = queue.size();%0A            for (int i = 0; i %3C size; i++) %7B%0A                TreeNode node = queue.poll();%0A                if (node.left != null) %7B%0A                    queue.offer(node.left);%0A                %7D%0A                if (node.right != null) %7B%0A                    queue.offer(node.right);%0A                %7D%0A                if (i == size - 1) %7B%0A                    res.add(node.val);%0A                %7D%0A            %7D%0A        %7D%0A        return res;%0A    %7D%0A%0A    /**%0A     * DFS. Backtracking.%0A     * Base case: if current node is null, just return.%0A     * Visit: if depth equals result size, means that it's at the correct level, add current node's value to result.%0A     * Next: recurse down next level with right node first and depth + 1. Then left node.%0A     * %3Cp%3E%0A     * Faster than BFS since there is no enqueue or dequeue.%0A     */%0A    public List%3CInteger%3E rightSideViewDFS(TreeNode root) %7B%0A        List%3CInteger%3E res = new ArrayList%3C%3E();%0A        helper(res, root, 0);%0A        return res;%0A    %7D%0A%0A    private void helper(List%3CInteger%3E res, TreeNode node, int depth) %7B%0A        if (node == null) %7B%0A            return;%0A        %7D%0A        if (depth == res.size()) %7B%0A            res.add(node.val);%0A        %7D%0A        helper(res, node.right, depth + 1); // Recurse right node first%0A        helper(res, node.left, depth + 1);%0A    %7D%0A%7D%0A

add Binary Tree Right Side View