Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create the root node of a tree.
DSA Go
root := &Node{Value: 10, [1]: nil, Left: nil, Right: nil} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Setting Parent to a non-nil value for root node.
✗ Incorrect
The root node has no parent, so its Parent field is nil.
2fill in blank
mediumComplete the code to check if a node is a leaf (no children).
DSA Go
func isLeaf(node *Node) bool {
return node.Left == nil && node.[1] == nil
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking Parent instead of Right child.
✗ Incorrect
A leaf node has no left or right children, so both Left and Right are nil.
3fill in blank
hardFix the error in the code to calculate the height of a node.
DSA Go
func height(node *Node) int {
if node == nil {
return -1
}
leftHeight := height(node.Left)
rightHeight := height(node.[1])
if leftHeight > rightHeight {
return leftHeight + 1
}
return rightHeight + 1
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Parent or Value instead of Right child.
✗ Incorrect
To find height, we check both Left and Right children recursively.
4fill in blank
hardFill both blanks to compute the depth of a node in the tree.
DSA Go
func depth(node *Node) int {
if node.[1] == nil {
return 0
}
return 1 + depth(node.[2])
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Left or Right child pointers instead of Parent.
✗ Incorrect
Depth is the number of edges from the node to the root, so we move up using Parent.
5fill in blank
hardFill all three blanks to create a map of node levels in the tree.
DSA Go
func assignLevels(node *Node, level int, levels map[*Node]int) {
if node == nil {
return
}
levels[node] = [1]
assignLevels(node.[2], level [3], levels)
assignLevels(node.Right, level+1, levels)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect level increments or decrements.
✗ Incorrect
We assign the current level to the node, then recurse on children with level + 1.