Java concise iterative: each level choose one node

  • 0
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> ans_l = new ArrayList<Integer>();
            Queue<TreeNode> ans_q = new LinkedList<TreeNode>();
            TreeNode top = null;
            if(root != null) ans_q.offer(root);
                int size = ans_q.size();
                for(int i = 0; i < size; i++){
                    top = ans_q.poll();
                    if(i == 0) ans_l.add(top.val);// add the right side node to the list
                    if(top.right != null) ans_q.add(top.right);
                    if(top.left != null) ans_q.add(top.left);
            return ans_l;

Log in to reply

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