Two Sum in BST with DFS and Hash Set

✅ Day 74 of 100 Days LeetCode Challenge Problem: 🔹 #653 – Two Sum IV: Input is a BST 🔗 https://lnkd.in/g9vDFKMA Learning Journey: 🔹 Today’s problem required checking whether there exist two nodes in a Binary Search Tree whose values sum to k. 🔹 I performed a Depth-First Search (DFS) traversal using a stack to visit all nodes of the tree. 🔹 While traversing, I stored each node’s value in a list. 🔹 Then I used a hash set to track visited values and checked whether the complement (k - value) already exists. 🔹 If the complement is found, it means two numbers sum to k, so the function returns True. Concepts Used: 🔹 Depth-First Search (DFS) 🔹 Stack-based Tree Traversal 🔹 Hash Set for Fast Lookup 🔹 Two Sum Pattern Key Insight: 🔹 The classic Two Sum approach works well after collecting values from the BST. 🔹 Using a set allows O(1) lookup, making it efficient to check complements during iteration. Complexity: 🔹 Time: O(n) 🔹 Space: O(n) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories