Java Iterative BFS Solution


  • 0
    X
    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            ArrayList<Integer> rsv = new ArrayList<Integer>();
            if(root == null)    return rsv;
            Queue<TreeNode> layer = new LinkedList<TreeNode>();
            layer.add(root);
            
            while(!layer.isEmpty()){
                TreeNode r = layer.poll();
                rsv.add(r.val);
                Queue<TreeNode> next_layer = new LinkedList<TreeNode>();
                if(r.right != null) next_layer.add(r.right);
                if(r.left != null) next_layer.add(r.left);
                while(!layer.isEmpty()){
                    TreeNode next = layer.poll();
                    if(next.right != null) next_layer.add(next.right);
                    if(next.left != null) next_layer.add(next.left);
                }
                layer = next_layer;
            }
            return rsv;
        }
    }

Log in to reply
 

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