0
0
DSA C++programming~30 mins

Path Sum Root to Leaf in Binary Tree in DSA C++ - Build from Scratch

Choose your learning style9 modes available
Path Sum Root to Leaf in Binary Tree
📖 Scenario: Imagine you have a family tree represented as a binary tree. Each person has a value representing their age. You want to find if there is a path from the oldest ancestor (root) down to a youngest descendant (leaf) where the sum of ages equals a specific number.
🎯 Goal: Build a program that checks if there exists a root-to-leaf path in a binary tree such that the sum of the node values along the path equals a given target sum.
📋 What You'll Learn
Create a binary tree node structure with integer values
Build a sample binary tree with exact node values
Create a target sum variable
Write a function to check if a root-to-leaf path sums to the target
Print the result as true or false
💡 Why This Matters
🌍 Real World
Checking path sums in trees is useful in decision trees, network routing, and financial modeling where paths represent sequences of choices or transactions.
💼 Career
Understanding tree traversal and recursion is fundamental for software engineers working with hierarchical data, algorithms, and system design.
Progress0 / 4 steps
1
Create the Binary Tree Node Structure and Build the Tree
Define a struct called TreeNode with an integer val, and two pointers left and right. Then create the following binary tree exactly: root node with value 5, left child 4, right child 8, left child of 4 is 11, left and right children of 11 are 7 and 2, right child of 8 is 4, and right child of this 4 is 1.
DSA C++
Hint

Start by defining the TreeNode struct with a constructor. Then create each node and link them exactly as described.

2
Create the Target Sum Variable
Inside main(), create an integer variable called targetSum and set it to 22.
DSA C++
Hint

Simply declare int targetSum = 22; inside main().

3
Write the Function to Check Path Sum
Write a function called hasPathSum that takes a TreeNode* called root and an integer sum. It returns true if there is a root-to-leaf path where the sum of node values equals sum, otherwise false. Use recursion and check if the current node is null, if it is a leaf, and subtract the node's value from sum as you go down.
DSA C++
Hint

Use recursion to check if the current node is null, then if it's a leaf check if sum == root->val. Otherwise, subtract root->val from sum and check left and right subtrees.

4
Print the Result of Path Sum Check
In main(), call hasPathSum(root, targetSum) and print true if it returns true, otherwise print false.
DSA C++
Hint

Call hasPathSum(root, targetSum) and print true if it returns true, else print false.