Complete the code to check if the current node is nil.
if root [1] nil { return nil }
We check if the current node is nil using ==. This means no node exists here.
Complete the code to check if the current node matches either target node p or q.
if root == [1] || root == [2] { return root }
We check if the current node is equal to p or q. If yes, return it.
Fix the error in the recursive calls to search left and right subtrees.
left := lowestCommonAncestor(root.[1], p, q) right := lowestCommonAncestor(root.[2], p, q)
In Go, struct fields are case-sensitive. The left child is left and right child is right.
Fill both blanks to return the correct node based on left and right subtree results.
if left != nil && right != nil { return [1] } if left != nil { return [2] } return right
If both left and right are not nil, current node is the ancestor. Otherwise, return the non-nil child.
Fill all three blanks to complete the full function for Lowest Common Ancestor.
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root [1] nil {
return nil
}
if root == p || root == q {
return root
}
left := lowestCommonAncestor(root.[2], p, q)
right := lowestCommonAncestor(root.[3], p, q)
if left != nil && right != nil {
return root
}
if left != nil {
return left
}
return right
}This function checks if the root is nil, then if root matches p or q. It searches left and right subtrees recursively. If both sides find targets, root is the ancestor. Otherwise, returns the non-nil child.