Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the queue with the root node.
DSA Go
queue := []*TreeNode[1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting with an empty queue
Using nil instead of root
✗ Incorrect
We start the traversal by putting the root node into the queue.
2fill in blank
mediumComplete the code to toggle the direction for zigzag traversal.
DSA Go
leftToRight = ![1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable name
Not toggling the direction
✗ Incorrect
We flip the boolean leftToRight to change the traversal direction after each level.
3fill in blank
hardFix the error in the code to append child nodes to the queue correctly.
DSA Go
if node.Left != nil { queue = append(queue, [1]) } if node.Right != nil { queue = append(queue, node.Right) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Appending wrong child
Appending nil
✗ Incorrect
We must append the left child node to the queue if it exists.
4fill in blank
hardFill both blanks to correctly reverse the level slice when needed.
DSA Go
if !leftToRight { for i, j := 0, len(level)-1; i < j; i, j = i+1, [1] { level[i], level[j] = level[j], level[i] } } queue = queue[[2]:]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Incorrect loop decrement
Wrong queue slicing
✗ Incorrect
We decrement j by 1 in the loop and remove the first element from the queue after processing.
5fill in blank
hardFill all three blanks to build the zigzag level order traversal correctly.
DSA Go
result := [][]int{}
queue := []*TreeNode[1]
leftToRight := true
for len(queue) > 0 {
levelSize := len(queue)
level := make([]int, levelSize)
for i := 0; i < levelSize; i++ {
node := queue[0]
queue = queue[[2]:]
if leftToRight {
level[i] = node.Val
} else {
level[levelSize-1-[3]] = node.Val
}
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
result = append(result, level)
leftToRight = !leftToRight
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Wrong queue initialization
Incorrect index usage
Not removing nodes from queue
✗ Incorrect
Start queue with root, remove one node each iteration, and place values correctly based on direction.