Skip to content

Instantly share code, notes, and snippets.

@pbesra
Created March 28, 2017 05:06
Show Gist options
  • Save pbesra/fc92431b12eab72d55a4b4311dd71096 to your computer and use it in GitHub Desktop.
Save pbesra/fc92431b12eab72d55a4b4311dd71096 to your computer and use it in GitHub Desktop.
Root to leaf sum binary tree
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MaximizeAction;
import java.lang.*;
import java.awt.List;
import java.io.*;
import java.time.*;
import java.math.*;
import java.rmi.Remote;
import java.sql.Array;
public class MyClass {
public static void main(String[] args)throws java.lang.Exception{
int[] a={12, 19, 18, 16, 14, 10, 34, 4, 13};
int x=26;
binary b1=new binary();
node root1=null;
for(int i=0;i<a.length;i++){
root1=b1.insert(a[i], root1);
}
ArrayList<Integer> ar=new ArrayList<>();
if(b1.Path(root1, x, ar)){
System.out.println("Found");
}else{
System.out.println("Not found");
}
Iterator<Integer> it=ar.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
class binary{
Queue<node> q=new LinkedList<node>();
public node insert(int x, node root){
if(root==null){
node temp=new node(x);
return root=temp;
}else if(x<=root.data){
root.left=insert(x, root.left);
}else{
root.right=insert(x, root.right);
}
return root;
}
public boolean Path(node root, int x, ArrayList<Integer> ar){
if(root==null){
return false;
}
if(root.right==null && root.left==null){
if(x==root.data){
ar.add(root.data);
return true;
}else{
return false;
}
}
if(Path(root.left, x-root.data, ar)){
ar.add(root.data);
return true;
}
if(Path(root.right, x-root.data, ar)){
ar.add(root.data);
return true;
}
return false;
}
}
class node{
int data;
node left, right;
public node(int x){
this.data=x;
this.left=null;
this.right=null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment