0
0
DSA Javascriptprogramming~30 mins

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

Choose your learning style9 modes available
Path Sum Root to Leaf in Binary Tree
📖 Scenario: Imagine you have a family tree where each person has a number representing their age. You want to check if there is a path from the oldest ancestor (root) down to a youngest family member (leaf) where the sum of ages equals a specific number.
🎯 Goal: Build a simple binary tree and write a function to check if there is a root-to-leaf path with a given sum.
📋 What You'll Learn
Create a binary tree node class called TreeNode with val, left, and right properties
Create a binary tree with exact nodes and values as specified
Create a variable called targetSum with the exact value specified
Write a function called hasPathSum that takes root and targetSum and returns true or false
Print the result of calling hasPathSum(root, targetSum)
💡 Why This Matters
🌍 Real World
Checking paths in trees is useful in decision-making systems, network routing, and family tree analysis.
💼 Career
Understanding tree traversal and recursion is important for software engineering roles involving data structures and algorithms.
Progress0 / 4 steps
1
Create the Binary Tree Node Class and Tree
Create a class called TreeNode with a constructor that takes val, left, and right parameters. Then create the binary tree with root node value 5, left child 4, right child 8, left child of 4 is 11, and left and right children of 11 are 7 and 2. The right child 8 has left child 13 and right child 4, and the right child 4 has right child 1. Store the root node in a variable called root.
DSA Javascript
Hint

Define the TreeNode class first, then build the tree from bottom to top using new TreeNode.

2
Set the Target Sum
Create a variable called targetSum and set it to 22.
DSA Javascript
Hint

Just create a variable targetSum and assign it the number 22.

3
Write the hasPathSum Function
Write a function called hasPathSum that takes parameters root and targetSum. It should return true if there is a root-to-leaf path in the tree where the sum of node values equals targetSum, otherwise false. Use recursion and check if the current node is null, if it is a leaf, and subtract the node value from targetSum as you go down.
DSA Javascript
Hint

Use recursion to check if the current node is a leaf and if the remaining sum equals the node's value. Otherwise, subtract the node's value and check left and right children.

4
Print the Result
Print the result of calling hasPathSum(root, targetSum).
DSA Javascript
Hint

Use console.log to print the result of hasPathSum(root, targetSum).