I'm building a recursive Java method to balance a binary search tree (using ints, but designed generic) using weights in each node. For my purpose, the weight of a node is defined as the number of children + 1.
2
/ \
1 3
The weight of the root is 3, and the weight of both leaves is 1.
At the end of the balancing, the value at any node should be the median of the values at all nodes in the subtree rooted at that node.
Here is my code:
public void weightBalance (BinarySearchTree<AnyType> t) {
// Base case
if (t.getRoot().left == null && t.getRoot().right == null) {
return;
}
// Get median of tree
AnyType median = t.getMedian();
// Create new BST with median as root
BinarySearchTree<AnyType> newTree = new BinarySearchTree<AnyType>();
newTree.insert(median);
// Insert all values except median into new BST
ArrayList<AnyType> stack = new ArrayList<AnyType>();
inorderTraverse(t.getRoot(), stack);
Iterator<AnyType> itr = stack.iterator();
while (itr.hasNext()) {
AnyType temp = itr.next();
if (temp != median) { // Comparing values or reference?
newTree.insert(temp);
}
}
// Replace old BST with new BST
t = newTree; // t is a copy of the reference, is this the problem?
// Recurse through children
// Tree constructor for reference:
// public BinarySearchTree (BinaryNode<AnyType> t) {
// root = t;
// }
if (t.getRoot().left != null) {
weightBalance(new BinarySearchTree(t.getRoot().left));
}
if (t.getRoot().right != null) {
weightBalance(new BinarySearchTree(t.getRoot().right));
}
}
I'm trying to modify the tree in place without returning anything, but the code does not change the tree. I know I'm messing by passing by reference and passing by value somewhere, but I can't figure out where - can anyone help out? I've spent a few hours debugging but I get really confused when debugging recursion.
Balancing algorithms are fairly common and well documented, e.g. TreeMap is a BST and you can see it source. I have never seen it use a copy of data, I doubt you need to create a stack or build a new tree just to balance it.
The normal behaviour is to rotate nodes, left or right, or a more complex combination of both. This reduces the work involved and doesn't create an garbage.
Related
I was looking at the code challenge from gfg BST to max heap:
Given a Binary Search Tree. Convert a given BST into a Special Max Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied on all the nodes in the so converted Max Heap.
I could not solve the challenge.
So I had a look at the following solution code:
class Solution
{
public static ArrayList<Integer> list=new ArrayList<>();
static int i=0;
public static void InOrderTraversal(Node root){
if(root == null) return ;
InOrderTraversal(root.left);
list.add(root.data);
InOrderTraversal(root.right);
}
public static void PostOrderTraversal(Node root){
if(root == null )return;
PostOrderTraversal(root.left);
PostOrderTraversal(root.right);
root.data= list.get(i);
i++;
}
public static void convertToMaxHeapUtil(Node root)
{
InOrderTraversal(root);
PostOrderTraversal(root);
}
}
I don't see how this code could change the structure of the tree, as it neither adds nor deletes any nodes.
Here is the second sample testcase copied from gfg official website:
Input BST:
3
/ \
1 5
\ / \
2 4 6
\
7
Expected Max heap output:
7
/ \
3 6
/ \ / \
1 2 4 5
I can't understand how it is working on that test case.
Driver code for the problem:
//{ Driver Code Starts
//Initial Template for Java
import java.util.LinkedList;
import java.util.Queue;
import java.io.*;
import java.util.*;
class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
left=null;
right=null;
}
}
class Tree {
static Node buildTree(String str){
if(str.length()==0 || str.charAt(0)=='N'){
return null;
}
String ip[] = str.split(" ");
// Create the root of the tree
Node root = new Node(Integer.parseInt(ip[0]));
// Push the root to the queue
Queue<Node> queue = new LinkedList<>();
queue.add(root);
// Starting from the second element
int i = 1;
while(queue.size()>0 && i < ip.length) {
// Get and remove the front of the queue
Node currNode = queue.peek();
queue.remove();
// Get the current node's value from the string
String currVal = ip[i];
// If the left child is not null
if(!currVal.equals("N")) {
// Create the left child for the current node
currNode.left = new Node(Integer.parseInt(currVal));
// Push it to the queue
queue.add(currNode.left);
}
// For the right child
i++;
if(i >= ip.length)
break;
currVal = ip[i];
// If the right child is not null
if(!currVal.equals("N")) {
// Create the right child for the current node
currNode.right = new Node(Integer.parseInt(currVal));
// Push it to the queue
queue.add(currNode.right);
}
i++;
}
return root;
}
static void postOrder(Node root)
{
if(root == null)
return;
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data+" ");
}
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t > 0){
String s = br.readLine();
Node root = buildTree(s);
Solution g = new Solution();
g.convertToMaxHeapUtil(root);
postOrder(root);
System.out.println();
t--;
}
}
}
// } Driver Code Ends
The code you have presented solves this problem with the knowledge that the output tree does not need to be a complete binary tree. Although the example output show a complete binary tree as output, this is not part of the requirement of the code challenge. The automated tests will only verify that the tree in the output has all the children nodes having lesser values than their parent nodes. It does not verify the shape of the tree.
The author of this solution had the insight to just keep the shape of the tree unchanged, with all its nodes staying where they are, and only move around values in that tree.
The approach to do this is simple: first the values (not the nodes!) are collected in a list with an in-order traversal. Since it is given that the input tree is a BST, the list will get the values in sorted order.
Then the values in that list are each assigned back to the node's data, overwriting their previous values. This time the nodes are visited in post-order, which means that parent nodes will get their values later than their child nodes will get them. Since the list is sorted, this means parent nodes will get greater values than their children have. This is exactly what the test suite will test.
We do note that this solves the challenge in maybe a surprising way, but it is not something you would want to do in practice, as a heap does not provide the expected efficiency if it is not balanced.
So if you had been trying to build a solution where you would get an efficient heap as output, then I can only praise that effort. This is what the goal should be of a programmer building a heap, and it shows why solving code challenges is not always helping one to improve on solving real life coding problems.
So I've been stuck for hours trying to figure out this problem.
Given a randomly generated BST and using the method header:
public E higher(E elt)
Where elt is a randomly generated value within the tree's range, I need to find the least element in the set greater than elt.
Nodes contain left links and right links, but no parent link.
The tree in the linked image reads with the root being the leftmost node
BST.
So if elt is 27, then I want to return the node containing 28.
I need to run this in O(logn) time, and everything I've tried has not worked.
I'm not looking for someone to do my homework for me, but I have no clue what to do at this point.
I can provide more detail and source code if it's needed.
Edit: I'll put this here, though it's woefully inadequate. I feel as though this would be easier if I could do this recursively but I can't think of a way to do that.
Node n = root;
//need to get this into a loop somehow and break out when I've found
//the right value
int c = myCompare(elt, ((E) n.data));
if (c < 0) {
n = n.left;
//now I need to compare this against any children
} else if (c > 0) {
n = n.right;
//now I need to compare this against any children
}
return ((E)n.data);
This depends on the fundamental property of BSTs: the left child is less than the parent, the right child is greater than the parent. If you look at a sample BST you will quickly notice a few properties, and you can see why the following algorithm will work.
If the current node is less than the given value, move right, otherwise move left. If you reach a point where moving left will give you a value that is too low (or you hit a leaf) then you found the correct node. Or, in pythonic pseudo-code:
while (true):
if (node.value <= elt):
node = node.right
else:
if (node.left.value < elt):
return node.value
else:
node = node.left
The pseudo-code obviously needs to check for errors, if a node is a leaf, etc., but this general algorithm will give you the expected output in the desired time complexity (assuming a balanced BST).
One possible approach is to find the specified node and to get the next least node from there (if you're allowed to use helper methods).
If we say that the root node is 'n' and we know that the desired value is inside the BST, then you can traverse through it to find the node that contains the given value with something like this:
public Node search(Node n, E obj)
{
if(obj.compareTo(n.getValue()) > 0)
{
return search(n.getRight(), obj);
}
else if(obj.compareTo(n.getValue()) < 0)
{
return search(n.getLeft(), obj);
}
else
{
return n;
}
}
If the objective were to retrieve the least value from a binary search tree, a simple recursive method like this would work:
public Node getLeast(node n)
{
if(n.getLeft()==null)
{
return n;
}
return getLeast(n.getLeft());
}
Using the principles of a binary search tree, we know that the least value greater than a given node is just the least node after the right child of the given node. So, we can just use this method to obtain the desired value:
getLeast(search(n,elt).getRight());
I have to create a function that took a tree t not empty, change the content of each leaf in its field by putting the sum of the values contained in the nodes of the path from the root to the leaf (including root and leaf).
So I created this:
void sum(BinTree t) {
while(!t.isLeaf()) {
sumL += sum(t.left);
sumR += sum(t.right);
}
t.element = ?;
}
boolean isLeaf(BinTree t) {
return t.left == null && t.right == null;
}
What should I put in place of "?"? I don't think that the function is correct..
I'm unable to create recursive functions for the binary trees, I find them very complicated..
Thanks
EDIT: I changhed my method:
void leafSum(BinTree t) {
sumLeaf(root, 0);
}
void leafSum(BinTree t, int tot) {
if(t->left == NULL && t->right == NULL)
t->elem = tot;
else {
sumLeaf(t->left, tot + t->elem);
sumLeaf(t->right, tot + t->elem);
}
}
Rather than providing a solution I'll give a few hints to help you along. Ask questions if any of it isn't clear.
The basic algorithm you are looking for is: for each node if it's a leaf then store the sum, if it's not a leaf then repeat for both child nodes.
While recursion isn't essential it will make the solution simpler in this case. It's not complex: the basic rule is to always have a termination condition (in your case, that you are looking at a leaf) before recursing.
You should pass a running total to the function so that you don't need to look back up the tree once you get to a leaf. That's not complex: just add the current value for the node to the running total before storing it (for leaves) or passing it to child node (for non-leaves).
Start with a running total of zero when you call the function for the root node.
That's about it - you should be able to come up with a solution from those hints.
I am trying to build a graph based on a linked list, where I build the linked list of nodes, and each node points to a linked list of edges. I build the graph based on an input file.
My input file will be on the following scheme:
Number of Nodes in graph
SourceNode1 EndNode1
SourceNode2 EndNode2
....
For example:
4 //Number of nodes
1 2 //An edge between 1 and 2
1 3 //An edge between 1 and 3
2 4 //An edge between 2 and 4
An assumption is that the nodes in the graph will numbered 1 through the number of nodes and that no node will have more than 1 "parent" (though a node might have more than 1 "child").
My problem is trying to build the linked list containing the nodes. Each node has 3 fields: the edges coming from that node, the node value (1, 2, 3, etc.), and the next node (because is a linked list of nodes). I attempt to parse in the number of nodes, create a first node manually, and attach the rest of the nodes in an in an iterative fashion.
Note: The parent field is for some external analysis unrelated to this question. You can ignore it.
Node class:
public class Node {
private Edge firstEdge;
private Node parent;
private Node nextNode;
private int element;
//Constructor
public Node() {
parent = null;
firstEdge = null;
nextNode = null;
}
//Accsessor and Modifier Methods
public void setElement(int e) {element = e;}
public Node getNextNode() {return nextNode;}
public Edge getFirstEdge() {return firstEdge;}
public void setFirstEdge(Edge a) {firstEdge = a;}
public void setNextNode(Node a) {nextNode = a;}
public int getElement() {return element;}
public Node getParent() {return parent;}
public void setParent(Node p) {parent = p;}
//Checks for a non-null parent
public boolean hasParent() { return parent == null; }
//checks iff node has next edge
public boolean hasFirstEdge() { return firstEdge == null; }
//checks if a node has a next node
public boolean hasNextNode() { return nextNode == null; }
}
Edge class:
public class Edge {
//Instance Variables
private Node nextNode;
private Edge nextEdge;
//Constructor
public Edge() {
nextNode = null;
nextEdge = null;
}
//Accsessor and Modifier Methods
public void setNextNode(Node a) {nextNode = a;}
public void setNextEdge(Edge a) {nextEdge = a;}
public Node getNextNode() {return nextNode;}
public Edge getNextEdge() {return nextEdge;}
public boolean hasNextEdge() {
return nextEdge == null;
}
}
Driver class:
import java.util.Scanner;
import java.io.*;
public class Driver {
public static void main(String[] args)throws FileNotFoundException{
//Get text file for building the graph
Scanner console = new Scanner(System.in);
System.out.print("Please enter the text file name: ");
String fileName = console.nextLine();
Scanner in = new Scanner(new File(fileName));
//in contains the file reading scanner
int numNodes = in.nextInt(); //first line of the text file
Node first = new Node(); //first is head of the list
first.setElement(1);
int i = 2; //counter
//Build the nodes list; I get problems in this loop
while (i <= numNodes) {
Node head = new Node(); //Tracker node
head = first; //head is the first node of the list
/*Loop to end of the list*/
while(head.hasNextNode()) {
//Null check; without it, I get NullPointerExceptions.
//If it is not needed, or there is a better way, please inform me.
if (head.getNextNode() == null) {
break;
}
head = head.getNextNode(); //get to the end of the ilst
}
//Next node to add
Node newNode = new Node();
newNode.setElement(i); //Because of the 1, 2, 3 nature of the graph
head.setNextNode(newNode); //Set the last element as the next node
i++;
}
//Manually check if graph is made (check if the nodes are linked correctly)
System.out.println("First elem (expect 1): " + first.getElement());
System.out.println("Second elem (expect 2): " + first.getNextNode().getElement()); //It prints 4 here for some reason
System.out.println("Third elem (expect 3): " + first.getNextNode().getNextNode().getElement()); //Getting a NullPointerException
System.out.println("Fourth elem (expect 4): " + first.getNextNode().getNextNode().getNextNode().getElement());
System.out.println("Expecting null: " + first.getNextNode().getNextNode().getNextNode().getNextNode().getElement());
}
When I'm checking if the graph is built, I get problems. I am manually checking it (for this small graph, its possible), and simply print out the first node and the value of the subsequent nodes. I am expecting 1, 2, 3, 4, and null (for the element past 4, because it does not exist). The first node is fine, it prints 1. Calling first.getNextNode().getElement() prints 4, for some odd reason. And calling the node after that gives a NullPointerException. Could someone help me solve this problem?
Note: I haven't added the edges yet. I am just trying to get the core of the linked list of nodes built.
This is my first post on stack overflow. I apologize if it is vague, ambigous, overly detailed, lacking in information, or is a duplicate question. I could not find the answer anywhere else. All input is welcome and appreciated.
Much of your naming is very confusing and is in serious need of clarifying refactorization. Edge's nextNode should be called destinationNode or something along those lines to make it clear you are dereferencing from an Edge object instead of from another Node.
Now, let's delve into the actual implementation.
Node head = new Node(); //Tracker node
head = first; //head is the first node of the list
What's going on here? It looks like you set your local variable head to be a brand new Node; that's great. Except the very next line, you discard it and set it to the value of your first variable.
Then you traverse all the way to the end of the list with a while loop, then create another new Node (this one you actually use). (Normally if you wanted to add something to the end of the list you should be utilizing a doubly linked list, or should at least have pointers to both the first and the last elements... i.e., first always stays the same, but when you add a new node you simply say newNode = new Node(); last.nextNode = newNode; last = newNode; and then configure the new element from there. The way you are doing it, it's taking O(N^2) time to construct a singly-linked list with N elements, hardly ideal.
I also have some preferential criticism about the construction of your minor classes... if you are allowing values to be freely get and set to any value with public setters and getters without taking any action whatsoever when they change, you get the exact same functionality from simply marking those fields public and doing away with the getters and setters entirely. If you have any plans to add more functionality in the future it's fine the way it is, but if they are just going to be dumb linked list elements whose actual uses are implemented elsewhere then you are better off treating the class more like a struct.
Here's a good way to build a singly-linked Node list the way you're looking to:
int numNodes = in.nextInt(); //first line of the text file
// sentinel value indicating the beginning of the list
Node header = new Node();
header.setElement(-1);
// last node in the list
Node last = first;
// this loop constructs a singly linked ring from the header
for (int i = 1; i <= numNodes; i++) {
Node newNode = new Node();
newNode.setElement(i);
newNode.setNextNode(header);
last.setNextNode(newNode);
last = newNode;
}
// do your debug outputs here
// for instance, this loop always outputs every node in the list:
for (Node n = header.getNextNode(); n != header; n = n.getNextNode()) {
System.out.println("Node " + n.getElement());
}
Note that the use of header as a sentinel value guarantees that for any Node that's already been built, getNextNode() will never return null.
Again, all this code can be made much more readable by making the fields in your Node and Edge classes public and scrapping the getters and setters. header.getNextNode().getNextNode().getNextNode() can become header.nextNode.nextNode.element and so forth.
Stage 2
Now that that's out of the way, we have the question of how useful this type of structure will actually be for your application. My biggest concern in looking at this is the fact that, when applying edges between nodes on your graph, you will need to access arbitrarily indexed Nodes to attach edges to them... and while every Node already knows what its element index is, getting the Nth node takes N steps because your entire set of nodes is in a linked list.
Remember, the main advantage of using a linked list is the ability to remove arbitrary elements in O(1) time as you step through the list. If you are only building a list and aren't going to ever remove anything from it, arrays are often faster -- especially if you ever need to access arbitrary elements.
What if you don't need to guarantee they're in any particular order or access them by their index, but you need to be able to add, access-by-ID, and remove them very quickly for larger data sets? HashSet may be the thing for you! What if you still need to be able to access them all in the order they were added? LinkedHashSet is your best friend. With this, you could easily even give the nodes names that are strings with no real slowdown.
As for the edges, I feel you are already doing fine: it's probably best to implement the outgoing edges for each Node in a singly linked list, assuming you will rarely be removing edges or will have a small number of edges per node and will always access them all together. To add a new edge, simply say newEdge = new Edge(); newEdge.nextEdge = firstEdge; firstEdge = newEdge; and you're done, having added the new edge to the beginning of the list. (Singly linked lists are easiest to use as stacks rather than queues.)
For extra fancy-points, implement Iterable<Edge> with your Node class and make a little Iterator class so you can use extended-for to visit every edge and make your life even easier!
As #Widdershins says, the terms used makes the algorithm hard to understand.
I would recommend two things in order to refactor your code:
Review the terminology (maybe this helps: http://en.wikipedia.org/wiki/Glossary_of_graph_theory). I know that it sounds like a silly recommendation, but using proper terms will help you a lot to review the object model.
Use a better representation. In your code a Node fills multiple roles, which makes the code hard to follow.
A good representation will depend a lot of the kind of problems that you try to resolve. For example an Adjacency List, or a Matrix are useful to apply some algorithms of graph theory.
But if you only want to exercise with an object oriented design, is useful to start with the basics.
Take the definition of a Graph in mathematics: G = (V, E)... a graph is a pair of a set of nodes and a set of edges between those nodes, and translate it to code:
(the example uses fields for brevity)
class DirectedGraph {
final Set<Node> nodes = new HashSet<Node>();
final Set<Edge> edges = new HashSet<Edge>();
}
Now you need to extend this definition. You can do it step by step. I did the same to end with this representation:
class DirectedGraph {
final Set<Node> nodes = new HashSet<Node>();
final Set<Edge> edges = new HashSet<Edge>();
public Node addNode(Object value) {
Node newNode = new Node(value);
nodes.add(newNode);
return newNode;
}
public Edge addEdge(Node src, Node dst) {
Edge newEdge = new Edge(src, dst);
edges.add(newEdge);
return newEdge;
}
private assertValidNode(Node n) {
if (n.graph != this)
throw new IllegalArgumentException("Node " + n + " not part of the graph");
}
public Set<Node> successorsOf(Node n) {
assertValidNode(n);
Set<Node> result = new HashSet<Node>();
for (Edge e : edges) {
if (e.src == n) { result.add(e.dst); }
}
return result;
}
class Node {
final graph = DirectedGraph.this;
final Object value;
Node(Object v) {
this.value = v;
}
public String toString() { return value.toString(); }
public Set<Node> successors() {
return graph.successorsOf(this);
}
// useful shortcut
public Node connectTo(Node... nodes) {
for (Node dst : nodes) {
graph.addEdge(this, dst);
}
return this;
}
}
class Edge {
final graph = DirectedGraph.this;
final Node src; final Node dst;
Edge(Node src, Node dst) {
graph.assertValidNode(src);
graph.assertValidNode(dst);
this.src = src; this.dst = dst;
}
public String toString() { return src.toString() + " -> " + dst.toString(); }
}
}
DirectedGraph g = new DirectedGraph();
DirectedGraph.Node one = g.addNode(1);
DirectedGraph.Node two = g.addNode(2);
DirectedGraph.Node three = g.addNode(3);
DirectedGraph.Node four = g.addNode(4);
one.connectTo(two, three)
two.connectTo(four);
System.out.println(g.edges);
System.out.println(one.successors());
System.out.println(two.successors());
This strategy of representing the domain model in a "1 to 1" mapping, always helped me to "discover" the object model. Then you can improve the implementation for your specific needs (i.e. the running time of successorsOf can be improved by using an adjacency list).
Note that in this representation a Node and an Edge can only exist as a part of a graph. This restriction is not deduced directly from the math representation... but helps to maintain the constraints of a proper graph.
Note You can extract the inner-classes by constructing the Node and Edge with a parent graph reference.
Hey, So I want to create a new tree which is basically the intersection (mathematical definition of intersection) of 2 given binary search trees. I have a method that prints out all the nodes at a particular level of the tree and I have a method that can find out the depth of the tree.I am pasting my work so far though it is incomplete and I'm stuck with the logic.Help will be appreciated.
public static Bst<Customer> intersect (Bst<Customer> a, Bst<Customer> b){
Bst<Customer> result = new Bst<Customer>();
BTNode<Customer> cur1;
BTNode<Customer> cur2;
BTNode<Customer> cur3;
cur1=a.root;
cur2=b.root;
cur3=result.root;
int Resultdepth;
if(a.maxDepth()<b.maxDepth())
Resultdepth=a.maxDepth();
else
Resultdepth=b.maxDepth();
if(cur1==null || cur2==null){ // Handeling the root case intially
result = null;
}
else
cur3.item.set_account_id(cur1.item.get_accountid()+ cur2.item.get_accountid());
cur1=cur1.left;
cur2=cur2.left;
cur3=cur3.left;
while(<some check>){
}
return result;
}
public int maxDepth(){
return mD(root);
}
int mD(BTNode<E> node){
if (node==null) {
return(0);
}
else {
int lDepth = mD(node.left);
int rDepth = mD(node.right);
// use the larger + 1
return(Math.max(lDepth, rDepth) + 1);
}
}
// for printing the nodes at a particular level and giving the starting level
public void PrintAt(BTNode<E> cur, int level, int desiredLevel) {
if (cur == null) {
return;
}
if (level == desiredLevel) {
System.out.print(cur.item.toString() + "");
}
else {
PrintAt(cur.left, level+1, desiredLevel);
PrintAt(cur.right, level+1, desiredLevel);
}
}
You have to traversal both trees in order at the same time and "in sync".
I'd suggest to implement the Iterable interface for your class. Then you get the first values from both trees. If they are equal, put it in the new tree, and get the next values from both iterators. If not, iterate the iterator with the smaller values until the value you get is as least as big as the last value from the other iterator. Rinse and repeat.
The intersection of two trees is presumably the nodes that are in both trees?
Given that you'll have to explore the tree to do this, why not just do an in-order traversal, store the nodes and then do an intersection operation on ordered lists?
My suggestion for such an intersection is simple:
Given tree A and tree B, to find tree C = A \intersect B:
1: Copy either tree A or B. Let us assume A for clarity.
This copy is now your tree C. Now let's 'trim' it.
2: For c = C.root_node and b = B.root_node:
if b==c,
Repeat the procedure with nodes b.left, c.left
Repeat the procedure with nodes b.right, c.right
else,
Remove c (thereby removing all subsequent children, it is implied they are unequal)
If this implementation would work, it would avoid the use of iterators and the like, and boil down to a simple recursive traversal.
(Like this!)
Ask if you would like further clarification.
Regards.
For the recursive implementation of finding intersection of two binary search trees , I came up with the following code. I am not very sure of the time complexity, but it does work all right.
void BST::findIntersection(cell *root1, cell * root2) {
if(root1 == NULL ) {
// cout<<"Tree 1 node is null , returning"<<endl;
return;
}
if(root2 == NULL) {
// cout<<"Tree 2 node is null , returning"<<endl;
return;
}
//cout<<"Comparing tree 1 : "<<root1->data<< " and tree 2 : " << root2->data<<endl;
if(root1->data==root2->data) {
// cout<<"tree 1 equal to tree 2 "<<endl;
insert(root1->data);
// cout<<"Inserting in new tree : "<<root1->data<<endl;
findIntersection(root1->left,root2->left);
findIntersection(root1->right, root2->right);
}
else if(root1->data>root2->data) {
// cout<<"tree 1 > tree 2 "<<endl;
findIntersection(root1,root2->right);
findIntersection(root1->left, root2);
}
else {
// cout<<"tree 1 < tree 2 "<<endl;
findIntersection(root1->right,root2);
findIntersection(root1, root2->left);
}
}