Created
September 26, 2021 04:03
-
-
Save Allan-Gong/76c8cd9bc7fd6b1498387c488fb5d763 to your computer and use it in GitHub Desktop.
BFS template - 199
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
// Tree level-traversal | |
// Graph - BFS | |
public List<Integer> rightSideView(TreeNode root) { | |
if (root == null) return Collections.emptyList(); | |
List<Integer> results = new ArrayList<>(); | |
Deque<TreeNode> queue = new LinkedList<>(); | |
queue.add(root); | |
while (!queue.isEmpty()) { | |
int size = queue.size(); | |
// System.out.println(queue); | |
// start looping elements of the current level | |
// this means the queue has all elements for the current level | |
results.add(queue.getLast().val); | |
for (int i = 0; i < size; i++) { | |
TreeNode node = queue.poll(); | |
if (node.left != null) queue.add(node.left); | |
if (node.right != null) queue.add(node.right); | |
} | |
} | |
return results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment