Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check whether a binary tree has the given path sum in C#?
A binary tree has a path sum when there exists a root-to-leaf path where the sum of all node values equals a given target sum. The HasPathSum method recursively traverses the tree, subtracting each node's value from the target sum until reaching a leaf node.
Syntax
Following is the syntax for checking path sum in a binary tree −
public bool HasPathSum(Node node, int targetSum) {
if (node == null) return false;
if (node.LeftChild == null && node.RightChild == null) {
return targetSum == node.Value;
}
int remainingSum = targetSum - node.Value;
return HasPathSum(node.LeftChild, remainingSum) ||
HasPathSum(node.RightChild, remainingSum);
}
How It Works
The algorithm works by recursively traversing each path from root to leaf. At each node, it subtracts the node's value from the target sum. When reaching a leaf node, it checks if the remaining sum equals zero, indicating a valid path sum exists.
Example
using System;
public class TreeNode {
public int Value;
public TreeNode LeftChild;
public TreeNode RightChild;
public TreeNode(int value) {
this.Value = value;
}
}
public class BinaryTreePathSum {
public bool HasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
// If it's a leaf node, check if remaining sum equals node value
if (root.LeftChild == null && root.RightChild == null) {
return targetSum == root.Value;
}
// Subtract current node value from target sum
int remainingSum = targetSum - root.Value;
// Recursively check left and right subtrees
return HasPathSum(root.LeftChild, remainingSum) ||
HasPathSum(root.RightChild, remainingSum);
}
public static void Main(string[] args) {
BinaryTreePathSum tree = new BinaryTreePathSum();
// Create binary tree: 5
// / \
// 2 6
// / \
// 1 3
TreeNode root = new TreeNode(5);
root.LeftChild = new TreeNode(2);
root.RightChild = new TreeNode(6);
root.LeftChild.LeftChild = new TreeNode(1);
root.LeftChild.RightChild = new TreeNode(3);
int targetSum = 8;
bool hasPath = tree.HasPathSum(root, targetSum);
Console.WriteLine("Has path sum " + targetSum + ": " + hasPath);
targetSum = 12;
hasPath = tree.HasPathSum(root, targetSum);
Console.WriteLine("Has path sum " + targetSum + ": " + hasPath);
targetSum = 15;
hasPath = tree.HasPathSum(root, targetSum);
Console.WriteLine("Has path sum " + targetSum + ": " + hasPath);
}
}
The output of the above code is −
Has path sum 8: True Has path sum 12: False Has path sum 15: False
Using Iterative Approach with Stack
Example
using System;
using System.Collections.Generic;
public class TreeNode {
public int Value;
public TreeNode LeftChild;
public TreeNode RightChild;
public TreeNode(int value) {
this.Value = value;
}
}
public class BinaryTreePathSumIterative {
public bool HasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
Stack<TreeNode> nodeStack = new Stack<TreeNode>();
Stack<int> sumStack = new Stack<int>();
nodeStack.Push(root);
sumStack.Push(targetSum - root.Value);
while (nodeStack.Count > 0) {
TreeNode currentNode = nodeStack.Pop();
int currentSum = sumStack.Pop();
// Check if it's a leaf node with sum = 0
if (currentNode.LeftChild == null && currentNode.RightChild == null && currentSum == 0) {
return true;
}
// Add left child to stack
if (currentNode.LeftChild != null) {
nodeStack.Push(currentNode.LeftChild);
sumStack.Push(currentSum - currentNode.LeftChild.Value);
}
// Add right child to stack
if (currentNode.RightChild != null) {
nodeStack.Push(currentNode.RightChild);
sumStack.Push(currentSum - currentNode.RightChild.Value);
}
}
return false;
}
public static void Main(string[] args) {
BinaryTreePathSumIterative tree = new BinaryTreePathSumIterative();
TreeNode root = new TreeNode(5);
root.LeftChild = new TreeNode(2);
root.RightChild = new TreeNode(6);
root.LeftChild.LeftChild = new TreeNode(1);
root.LeftChild.RightChild = new TreeNode(3);
Console.WriteLine("Iterative approach - Has path sum 8: " + tree.HasPathSum(root, 8));
Console.WriteLine("Iterative approach - Has path sum 10: " + tree.HasPathSum(root, 10));
}
}
The output of the above code is −
Iterative approach - Has path sum 8: True Iterative approach - Has path sum 10: True
Comparison of Approaches
| Approach | Time Complexity | Space Complexity | Advantages |
|---|---|---|---|
| Recursive | O(n) | O(h) - height of tree | Simple, clean code |
| Iterative with Stack | O(n) | O(n) - explicit stack | No recursion depth limits |
Conclusion
Checking for path sum in a binary tree involves traversing root-to-leaf paths while tracking the remaining target sum. Both recursive and iterative approaches achieve O(n) time complexity, with the recursive solution being more intuitive and the iterative approach avoiding potential stack overflow issues for deep trees.
