My 2ms Level Order ,Easy to Uderstand


  • 4
    X

    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>();
          queue.add(root);
          while(queue.size()!=0){
            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.