Complete the code to create a queue for BFS traversal.
let mut queue = VecDeque::new();
queue.[1](root);We use push_back to add the root node at the end of the queue for BFS.
Complete the code to remove the front node from the queue during BFS.
while let Some(node) = queue.[1]() { // process node }
We use pop_front to remove the node at the front of the queue for BFS traversal.
Fix the error in adding child nodes to the queue during BFS traversal.
if let Some(left) = node.left.as_ref() { queue.[1](left); }
We add child nodes to the back of the queue using push_back to maintain BFS order.
Fill both blanks to correctly collect node values and enqueue children in BFS.
let mut result = Vec::new(); while let Some(node) = queue.pop_front() { result.push(node.[1]); if let Some(left) = node.left.as_ref() { queue.[2](left); } }
value.push_front which breaks BFS order.We access the node's value with val and add children to the queue with push_back.
Fill all three blanks to complete BFS traversal collecting all node values.
use std::collections::VecDeque;
fn level_order(root: Option<&Box<TreeNode>>) -> Vec<i32> {
let mut result = Vec::new();
if root.is_none() {
return result;
}
let mut queue = VecDeque::new();
queue.[1](root.unwrap());
while let Some(node) = queue.pop_front() {
result.push(node.[2]);
if let Some(left) = node.left.as_ref() {
queue.[3](left);
}
}
result
}pop_front to add elements instead of removing.push_front which breaks BFS order.We enqueue the root with push_back, access node value with val, and enqueue children with push_back.
