0
0
DSA Goprogramming~30 mins

Two Sum in BST in DSA Go - Build from Scratch

Choose your learning style9 modes available
Two Sum in BST
📖 Scenario: You are working with a phone book stored as a Binary Search Tree (BST). Each node contains a phone number. You want to find if there are two phone numbers in the BST that add up to a specific target sum.
🎯 Goal: Build a program that creates a BST with given phone numbers, sets a target sum, checks if any two numbers in the BST add up to the target, and prints the result.
📋 What You'll Learn
Create a BST with exact phone numbers: 10, 5, 15, 3, 7, 18
Create a variable called target with value 22
Write a function findTarget that returns true if two numbers in the BST add up to target
Print true or false depending on the result
💡 Why This Matters
🌍 Real World
Finding pairs of numbers that sum to a target is useful in financial applications, phone number analysis, and data validation.
💼 Career
This problem helps prepare for coding interviews and teaches tree traversal and hash map usage, common in software engineering roles.
Progress0 / 4 steps
1
Create the BST nodes
Create a struct type called TreeNode with fields Val int, Left *TreeNode, and Right *TreeNode. Then create the BST root node called root with value 10, and add nodes with values 5, 15, 3, 7, and 18 as shown in the example.
DSA Go
Hint

Define the TreeNode struct first. Then create the root node and link child nodes to build the BST.

2
Set the target sum
Create an integer variable called target and set it to 22.
DSA Go
Hint

Just write target := 22 inside the main function.

3
Write the function to find two sum in BST
Write a function called findTarget that takes root *TreeNode and k int as parameters and returns bool. Use a map to store visited values and check if k - current node value exists. Traverse the BST recursively.
DSA Go
Hint

Use a helper function dfs inside findTarget to traverse the tree recursively. Use a map to check if the complement exists.

4
Print the result
Print the value of result using fmt.Println(result).
DSA Go
Hint

Use fmt.Println(result) to print the boolean result.