level order traversal solution in Java
public class Solution { public List<Integer> rightView(TreeNode root) { // Write your solution here List<Integer> view = new ArrayList<>(); if(root==null){ return view; } Queue<TreeNode> layer = new LinkedList<>(); layer.offer(root); while(layer.size()>=1){ int count = layer.size(); for(int i = 0; i<count; i++){ TreeNode curNode = layer.poll(); if(curNode.left!=null){ layer.offer(curNode.left); } if(curNode.right!=null){ layer.offer(curNode.right); } if(i == count-1){ view.add(curNode.key); } } } return view; } }
time: O(n) we do O(1) operation to each treeNode
space: O(n) use to keep our result:O(n) queue to store treeNode: O(n)