"Day 35: LeetCode 112 - Path Sum in a Binary Tree"

✅ Day 35 of #100DaysOfCode Challenge 📘 LeetCode Problem 112: Path Sum 🧩 Problem Statement: Given the root of a binary tree and an integer targetSum, return true if there exists a root-to-leaf path whose sum of node values equals targetSum. Example: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: Path 5 → 4 → 11 → 2 gives the sum = 22 ✅ 💡 Simple Approach: If the tree is empty → return false If it’s a leaf node → check if its value equals targetSum Otherwise → subtract node value and check left and right recursively 💻 Easiest Java Code: class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; if (root.left == null && root.right == null && root.val == sum) return true; sum = sum - root.val; return hasPathSum(root.left, sum) || hasPathSum(root.right, sum); } } ⚙️ Complexity: ⏱️ Time: O(n) → visit each node once 💾 Space: O(h) → recursion stack (h = height of tree) 🌿 Small code, big concept — recursion makes trees easy 🌱 #Day35 #100DaysOfCode #LeetCode #Java #DSA #BinaryTree #Recursion #CodingChallenge

  • graphical user interface, text, application, chat or text message

To view or add a comment, sign in

Explore content categories