Java BFS solution

  • 0

    the space required is the max number of nodes on each level. while DFS max space is the height of tree.

        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            if (root != null) {
                List<TreeNode> level = new ArrayList<>();
                while (!level.isEmpty()) {
                    List<TreeNode> nextLevel = new ArrayList<>();
                    for (TreeNode node : level) {
                        if (node.left != null) nextLevel.add(node.left);
                        if (node.right != null) nextLevel.add(node.right);
                    result.add(level.get(level.size() - 1).val);
                    level = nextLevel;
            return result;

Log in to reply

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