Skip to content

BFS-2 complete#1577

Open
Nikesh46 wants to merge 1 commit intosuper30admin:masterfrom
Nikesh46:master
Open

BFS-2 complete#1577
Nikesh46 wants to merge 1 commit intosuper30admin:masterfrom
Nikesh46:master

Conversation

@Nikesh46
Copy link
Copy Markdown

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

Your solution for the Right Side View problem is correct and efficient. Well done! However, note that you included code for a different problem (Leetcode993) in the same file. In the future, make sure to submit only the code for the problem you are solving.

To improve code clarity:

  1. Consider renaming "q" to "queue" for better readability.
  2. The inner while loop can be replaced with a for loop that runs from 0 to size-1, which might make the intention clearer (as in the reference solution).
  3. The comment at the top says "DFS Solution", but your code uses BFS. Please correct the comment to avoid confusion.

Here's a slight refactor of your code for clarity (without changing the logic):

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == size - 1) {
                    res.add(node.val);
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        return res;
    }
}

This uses a for loop which is more common for level-order traversal.

@Nikesh46
Copy link
Copy Markdown
Author

Quick Question - Leetcode993 contains isCousins problem which was one of the questions in BFS-2. Please let me know if I am missing something here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants