public class SearchNodewithoutRecursion {
public static void main(String args[]) {
Node node = new Node(1);
node.left = new Node(2);
node.right = new Node(3);
node.left.left = new Node(4);
node.left.right = new Node(5);
node.right.left = new Node(6);
node.right.right = new Node(7);
SearchNodewithoutRecursion searchANodeUsingRecusrsion = new SearchNodewithoutRecursion();
int val = searchANodeUsingRecusrsion.findNode(node, 4);
if(val==1)
System.out.println("found");
else
System.out.println("not found");
}
public int findNode(Node node, int key) {
if(null!=node) {
Queue<Node> queue = new LinkedBlockingQueue<>();
queue.add(node);
while(!queue.isEmpty()) {
Node temp = queue.remove();
System.out.println(temp.value);
if(temp.value == key) {
return 1;
}
if(null!=temp.left) {
queue.add(temp.left);
}
if(null!=temp.right) {
queue.add(temp.right);
}
}
}
return 0;
}
}
class BinayTree{
static class Node{
String value;
Node left;
Node right;
Node(String val){
value = val;
left = right = null;
}
}
}
public static void main(String args[]) {
Node node = new Node(1);
node.left = new Node(2);
node.right = new Node(3);
node.left.left = new Node(4);
node.left.right = new Node(5);
node.right.left = new Node(6);
node.right.right = new Node(7);
SearchNodewithoutRecursion searchANodeUsingRecusrsion = new SearchNodewithoutRecursion();
int val = searchANodeUsingRecusrsion.findNode(node, 4);
if(val==1)
System.out.println("found");
else
System.out.println("not found");
}
public int findNode(Node node, int key) {
if(null!=node) {
Queue<Node> queue = new LinkedBlockingQueue<>();
queue.add(node);
while(!queue.isEmpty()) {
Node temp = queue.remove();
System.out.println(temp.value);
if(temp.value == key) {
return 1;
}
if(null!=temp.left) {
queue.add(temp.left);
}
if(null!=temp.right) {
queue.add(temp.right);
}
}
}
return 0;
}
}
class BinayTree{
static class Node{
String value;
Node left;
Node right;
Node(String val){
value = val;
left = right = null;
}
}
}
No comments:
Post a Comment