Java very simple, level order traversal, last one at each level is visible from right.


  • -1
    J
     public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if (root == null)
        	return ans;
        
        // level order traversal.
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
        	int n = q.size();
        	while (n-- > 0) {
        		TreeNode node = q.poll();
        		if (n == 0)  //Last node at the current level, visible from right.
        			ans.add(node.val);
        		if (node.left != null)
        			q.offer(node.left);
        		if (node.right != null)
        			q.offer(node.right);
        	}
         }
        return ans;
    }

Log in to reply
 

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