Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@thmain
Created February 25, 2016 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/b19ade530eb541fa989b to your computer and use it in GitHub Desktop.
Save thmain/b19ade530eb541fa989b to your computer and use it in GitHub Desktop.
public class ExistPathSum {
String path;
public void hasPath(Node root, int sum, String path){
if(root!=null){
if(root.data>sum){ // if root is greater than Sum required, return
return;
}else{
path+=" " + root.data; //add root to path
sum=sum-root.data; // update the required sum
if(sum==0){ //if sum required =0, means we have found the path
System.out.println(path);
}
hasPath(root.left, sum, path);
hasPath(root.right, sum, path);
}
}
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(7);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
ExistPathSum i = new ExistPathSum();
i.hasPath(root, 10, "");
}
}
class Node {
int data;
Node left, right;
public Node(int data) {
this.data = data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment