Java solution for Sum Root to Leaf Numbers using DFS

🚀 Day 399 of #500DaysOfCode 🔹 Problem: 129. Sum Root to Leaf Numbers 🔹 Difficulty: Medium 🔹 Language Used: Java ☕ 🧩 Problem Summary: Given the root of a binary tree containing digits (0–9), each root-to-leaf path represents a number. Our task is to find the sum of all numbers formed by these root-to-leaf paths. 💡 Key Idea: We can use Depth-First Search (DFS) to traverse the tree. As we go deeper, we build the current number by multiplying by 10 and adding the current node’s value. When we reach a leaf node, we add that full number to our total sum. ⚙️ Approach: 1️⃣ Start DFS from the root with currentSum = 0. 2️⃣ At each step, update currentSum = currentSum * 10 + node.val. 3️⃣ When reaching a leaf node, return that number. 4️⃣ Combine left and right subtree results to get the total sum. ✅ Example: Input: root = [1,2,3] Output: 25 Paths: 12 + 13 = 25 📘 Lesson Learned: Sometimes, problems that seem about “trees” are really about number construction — a great reminder that recursion can elegantly combine logic with mathematics 🌱 #Day399 #Java #LeetCode #BinaryTree #DFS #ProblemSolving #CodingChallenge #LearnEveryday #Programming #Developer #500DaysOfCode

  • text

To view or add a comment, sign in

Explore content categories