2ms Java BFS solution, easy to understand


  • 1
    Y
    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            // Write your solution here.
            // 1:39pm - 1:44pm
            List<Integer> result = new ArrayList<Integer>();
            if (root == null) {
                return result;
            }
            LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);
            while (! queue.isEmpty() ) {
                int size = queue.size();
                for (int i = 0; i < size ; i++) {
                    TreeNode curr = queue.poll();
                    if (i == size - 1) {
                        result.add(curr.val);
                    }
                    if (curr.left != null) {
                        queue.offer(curr.left);
                    }
                    if (curr.right != null) {
                        queue.offer(curr.right);
                    }
                }
            }
            return result;
        }
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.