C Program: Determine Binary Tree path with parget sum
9. Root-to-Leaf Path Sum Challenges
Write a C program to determine if a binary tree has a root-to-leaf path whose sum equals a given target sum.
Sample Solution:
C Code:
Output:
Path with sum 18 exists in the binary tree.
Explanation:
In the exercise above,
- Structure Definition:
- struct TreeNode: Represents a binary tree node with integer data and pointers to left and right children.
- Node Creation Function:
- createNode: Allocates memory for a new node, initializes its data, and sets left and right pointers to 'NULL'.
- Path Sum Checking Function:
- hasPathSum: Checks if there is a path from the root to any leaf node in the binary tree such that the sum of node values along the path equals the given 'targetSum'.
- Recursively explores the left and right subtrees.
- Tree Traversal and Sum Comparison:
- The main function builds a sample binary tree.
- Sets a targetSum variable.
- Calls hasPathSum to check if a path with the specified sum exists.
- Prints a message indicating whether such a path exists or not.
- Memory Deallocation Function:
- freeTree: Frees the memory allocated for the binary tree nodes.
- Sample Binary Tree in Main:
- Constructs a binary tree with integer values.
- Sets a target sum.
- Checks if there is a path in the tree with a sum equal to the target sum.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to find and print all root-to-leaf paths in a binary tree that sum up to a given target value.
- Write a C program to count the number of root-to-leaf paths that equal a specified sum, handling negative numbers as well.
- Write a C program to identify the shortest root-to-leaf path that matches a given target sum.
- Write a C program to determine if there exists any root-to-leaf path with a given sum using backtracking techniques.
C Programming Code Editor:
Previous: C Program: Expression Tree from Postfix Expression and Evaluation.
Next: Implementing AVL Tree in C: Insertion and Deletion Operations.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.