Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new binary tree node with given value.
DSA Go
func newNode(val int) *Node {
return &Node{
data: [1],
left: nil,
right: nil,
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name not defined in the function like 'value' or 'node'.
✗ Incorrect
The function parameter is named 'val', so we assign 'val' to the node's data field.
2fill in blank
mediumComplete the code to check if a node is a leaf node (no children).
DSA Go
func isLeaf(node *Node) bool {
return node != nil && node.left == nil && node.[1] == nil
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking a non-existent field like 'child' or 'parent'.
✗ Incorrect
A leaf node has both left and right children as nil, so we check node.right == nil.
3fill in blank
hardFix the error in the code to traverse the left boundary of the tree (excluding leaves).
DSA Go
func addLeftBoundary(root *Node, res *[]int) {
curr := root.left
for curr != nil {
if !isLeaf(curr) {
*res = append(*res, curr.data)
}
if curr.left != nil {
curr = curr.[1]
} else {
curr = curr.right
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using curr.right instead of curr.left when left child exists.
✗ Incorrect
To traverse the left boundary, we move down the left child if it exists.
4fill in blank
hardFill both blanks to add the right boundary nodes in reverse order (excluding leaves).
DSA Go
func addRightBoundary(root *Node, res *[]int) {
curr := root.[1]
var tmp []int
for curr != nil {
if !isLeaf(curr) {
tmp = append(tmp, curr.data)
}
if curr.[2] != nil {
curr = curr.[2]
} else {
curr = curr.left
}
}
for i := len(tmp) - 1; i >= 0; i-- {
*res = append(*res, tmp[i])
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from root.left or moving down left children for right boundary.
✗ Incorrect
Start from root.right and move down right children to collect right boundary nodes.
5fill in blank
hardFill all three blanks to collect all leaf nodes in left-to-right order.
DSA Go
func addLeaves(root *Node, res *[]int) {
if root == nil {
return
}
if isLeaf(root) {
*res = append(*res, root.[1])
return
}
addLeaves(root.[2], res)
addLeaves(root.[3], res)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Appending wrong field like 'value' or traversing right child before left.
✗ Incorrect
Append the data of leaf nodes and recursively traverse left then right children.