Question

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

一刷

  1. BFS
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
     public List<Integer> rightSideView(TreeNode root) {
         List<Integer> result = new ArrayList<>();
         if(root == null) return result;
         LinkedList<TreeNode> q = new LinkedList<>();
         q.add(root);
         while(!q.isEmpty()){
             int n = q.size();
             for(int i = 0; i < n; i++){
                 TreeNode temp = q.poll();
                 if(i == n - 1) result.add(temp.val);
                 if(temp.left != null) q.add(temp.left);
                 if(temp.right != null) q.add(temp.right);
             }
         }
         return result;
     }
    }
    

二刷

  1. 一刷的时候读取数据不够优雅。
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
     public List<Integer> rightSideView(TreeNode root) {
         List<Integer> result = new LinkedList<>();
         if(root == null) return result;
         LinkedList<TreeNode> q = new LinkedList<>();
         q.add(root);
         while(!q.isEmpty()){
             int size = q.size();
             TreeNode node = null;
             for(int i = 0; i < size; i++){
                 node = q.poll();
                 if(node.left != null) q.add(node.left);
                 if(node.right != null) q.add(node.right);
             }
             result.add(node.val);
         }
         return result;
     }
    }
    

Amazon session

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root == null) return result;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            int size = q.size();
            for(int p = 0; p < size; p++){
                TreeNode node = q.poll();
                if(p == size - 1) result.add(node.val);
                if(node.left != null) q.offer(node.left);
                if(node.right != null) q.offer(node.right);
            }
        }
        return result;
    }
}