Home › Company-wise questions › Microsoft › Path Sum ← Microsoft bank
Microsoft · Question 44 · Trees
Path Sum Trees Java code ⏱ O(n) 💾 O(h)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
Problem Given a target sum, determine if there is a path from root to leaf with that sum.
Approach Subtract node values downward; only a matching leaf finishes.
Time O(n)Space O(h)
How it works 1 Carry the remaining sum downward. 2 Only a leaf may finish the path. Sample input / output Input:
13 22
5 4 8 11 x 13 4 7 2 x x x 1
Output:
true Constraints 0 <= nodes <= 5000.
Solution — read it, then walk it Flowchart Pseudocode
Time O(n)Space O(h)Loops 2Branches 5Returns 3source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
yes no ↻ repeat ↻ repeat START import java.util.* DEFINE class Main DEFINE static boolean hasPathSum(TreeNode root, int sum) if (root == null) return false if (root.left == null && root.right == null) RETURN sum == root.val RETURN hasPathSum(root.left, sum - root.val) |… DEFINE class TreeNode DEFINE val TreeNode left, right TreeNode(int v) { val = v; } DEFINE TreeNode buildTree(Integer[] values) if (values.length == 0 || values[0] == null) return null TreeNode root = new TreeNode(values[0]) java.util.Queue<TreeNode> q = new java.util.LinkedList<>() q.offer(root) DEFINE i = 1 while (!q.isEmpty() && i < values.length) TreeNode node = q.poll() if (i < values.length && values[i] != null) { node.left = ne… i++ if (i < values.length && values[i] != null) { node.right = ne… i++ RETURN root DEFINE static void main(String[] args) java.util.Scanner sc = new java.util.Scanner(System.in) DEFINE n = sc.nextInt(); int target = sc.nextInt() Integer[] vals = new Integer[n] for (int i = 0; i < n; i++) String t = sc.next() vals[i] = t.equals("x") ? null : Integer.parseInt(t) TreeNode root = buildTree(vals) System.out.println(hasPathSum(root, target)) END start / end statement condition loop returns definition← Q43 · Symmetric Tree Q45 · Kth Smallest Element in a BST → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →