How to check whether a binary tree has the given path sum in C#?


HasPathsum takes 2 parameters one is the tree node and other is the sum value, initially we check whether the node is null or not, if the node is null then we return false. If the node is not null then we call HasPathSum recursive method, in each and every recursive step we keep on subtracting the sum value from the node value. If the value of the sum reaches 0 then we come to conclusion that the given tree has the path that is equal to sum and return true.

Example

public class TreesPgm{
   public class Node{
      public int Value;
      public Node LeftChild;
      public Node RightChild;
      public Node(int value){
         this.Value = value;
      }
      public override String ToString(){
         return "Node=" + Value;
      }
   }
   public bool HasPathSum(Node node, int sum){
      if (root == null){
         return false;
      }
      return helperHasPathSum(node, sum);
   }
   private bool helperHasPathSum(Node root, int sum){
      if (root == null){
         return false;
      }
      sum -= root.Value;
      if (root.LeftChild == null && root.RightChild == null && sum == 0){
         return true;
      }
      return helperHasPathSum(root.LeftChild, sum) || helperHasPathSum(root.RightChild, sum);
   }
}

Input

         5
      2    6
   1    3
7

Output

True

Updated on: 17-Aug-2021

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements