Simple iterative java solution using queue.


  • 0
    F
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> res = new LinkedList<>();
            if(root == null)
                return res;
            Queue<TreeNode> queue = new LinkedList<>();
            int cNums = 1, nNums = 0; // cNums; number of nodes in current level. nNums: next level
            queue.add(root);
            while(!queue.isEmpty()){
                TreeNode curr = queue.remove();
                cNums--;
                if(curr.left!=null){
                    queue.add(curr.left);
                    nNums++;
                }
                if(curr.right!=null){
                    queue.add(curr.right);
                    nNums++;
                }
                if(cNums == 0){
                    res.add(curr.val);         // curr is the right node of current level.
                    cNums = nNums;
                    nNums = 0;
                }
            }
            return res;
        }
    

Log in to reply
 

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