Simple Java answer


  • 0
    B
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> results = new ArrayList<>();
        List<TreeNode> levels = new ArrayList<>();
        if (root != null) {
            levels.add(root);
        }
        while (levels.size() > 0) {
            results.add(levels.get(levels.size() - 1).val);
            List<TreeNode> newLevels = new ArrayList<>();
            for (TreeNode node: levels) {
                if (node.left != null) newLevels.add(node.left);
                if (node.right != null) newLevels.add(node.right);
            }
            levels = newLevels;
        }
        
        return results;
    }

Log in to reply
 

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