Java iterative solution! cur is always the rightest TreeNode!


  • 0
    B
    public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root == null) {
            return result;
        }
        Deque<TreeNode> queue = new LinkedList<>();
        TreeNode cur = root;
        while(cur != null) {
            result.add(cur.val);
            int size = queue.size();
            do {
                if(cur.right != null) {
                    queue.addLast(cur.right);
                }
                if(cur.left != null) {
                    queue.addLast(cur.left);
                }
                cur = queue.pollFirst();
                size--;
            } while(size >= 0);
        }
        return result;
    }
    

    }


Log in to reply
 

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