Short Java BFS solution


  • 0
    T
    public List<Integer> rightSideView(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        List<Integer> result = new ArrayList<Integer>();
        while (!queue.isEmpty()) {
            Integer rightSide = null;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode q = queue.pollFirst();
                if (q == null)
                    continue;
                rightSide = q.val;
                queue.add(q.left);
                queue.add(q.right);
            }
            if (rightSide != null)
                result.add(rightSide);
        }
        return result;
    }

Log in to reply
 

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