My 2ms Level Order ,Easy to Uderstand

  • 4

    Using level Order Travaling:Travel each level ,find the last TreeNode of the level and add its val into our result .

    public class Solution {

      public List<Integer> rightSideView(TreeNode root) {
          List<Integer> res=new ArrayList<Integer>();
          if(root==null) return res;
          Queue<TreeNode> queue=new LinkedList<TreeNode>();
            int level=queue.size();
            for(int i=1;i<=level;i++){
               TreeNode temp=queue.poll();
               if(level==i) res.add(temp.val);
               if(temp.left!=null) queue.add(temp.left);
               if(temp.right!=null) queue.add(temp.right);
        return res;


Log in to reply

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