Java solution based on the Level order


  • 0
    H

    '''

    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) return res;
        Queue<TreeNode> que = new LinkedList<TreeNode>();
        que.offer(root);
        res.add(root.val);
        int pre = 1;
        boolean visual = true;
        
        while(!que.isEmpty()){
            TreeNode cur = que.poll();
            pre --;
            
            if (cur.right != null){
                if(visual) {
                    res.add(cur.right.val);
                    visual = false;
                }
                que.offer(cur.right);
            }
            
            if (cur.left != null){
                if (visual){
                    res.add(cur.left.val);
                    visual = false;
                }
                que.offer(cur.left);
            }
            
            if (pre == 0){
                pre = que.size();
                visual = true;
            }
        }
        
        return res;
    }
    

    '''


Log in to reply
 

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