199. Binary Tree Right Side View

Link

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       <---

Solution

這題同103, 107,是類似的問題,唯一的差別是指處理該level第一個被travel的node

    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ret = new LinkedList<>();
        if(root == null) return ret;
        Queue<TreeNode> que = new LinkedList<>();
        que.add(root);
        while(!que.isEmpty()){
            int number = que.size();
            for(int i = 0; i < number; i++){
                TreeNode node = que.poll();
                if(i == 0){
                    ret.add(node.val);
                }
                if(node.right != null){
                    que.add(node.right);
                }
                if(node.left != null){
                    que.add(node.left);
                }
            }
        }
        return ret;
    }

Last updated

Was this helpful?