package in.blogspot.arunj2ee.ds.tree.binary.que;
import in.blogspot.arunj2ee.ds.tree.BinaryTreeNode;
import in.blogspot.arunj2ee.ds.tree.util.BTreePrinter;
import in.blogspot.arunj2ee.ds.tree.util.TreeUtil;
import java.util.LinkedList;
import java.util.Queue;
/*
* Que: Give an algorithm for searching an element in binary tree without using recursion
* Time Complexity: O(n), Space Complexity: O(n)
*/
public class Que4 {
public static boolean findInBT(BinaryTreeNode root, int data){
if(root == null)
return false;
if(root.getData() == data)
return true;
Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>();
q.offer(root);
while(!q.isEmpty()){
BinaryTreeNode tmp = q.poll();
if(tmp.getData() == data)
return true;
if(tmp != null){
if(tmp.getLeft() != null)
q.offer(tmp.getLeft());
if(tmp.getRight() != null)
q.offer(tmp.getRight());
}
}
return false;
}
public static void main(String[] args) {
BinaryTreeNode rootNode = TreeUtil.createRandomBinaryTree();
BTreePrinter.printBinaryTreeNode(rootNode);
for(int i=0;i<20;i++){
System.out.println(i + " Value found: " + findInBT(rootNode,i));
}
}
}
========================================================================
import in.blogspot.arunj2ee.ds.tree.BinaryTreeNode;
import in.blogspot.arunj2ee.ds.tree.util.BTreePrinter;
import in.blogspot.arunj2ee.ds.tree.util.TreeUtil;
import java.util.LinkedList;
import java.util.Queue;
/*
* Que: Give an algorithm for searching an element in binary tree without using recursion
* Time Complexity: O(n), Space Complexity: O(n)
*/
public class Que4 {
public static boolean findInBT(BinaryTreeNode root, int data){
if(root == null)
return false;
if(root.getData() == data)
return true;
Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>();
q.offer(root);
while(!q.isEmpty()){
BinaryTreeNode tmp = q.poll();
if(tmp.getData() == data)
return true;
if(tmp != null){
if(tmp.getLeft() != null)
q.offer(tmp.getLeft());
if(tmp.getRight() != null)
q.offer(tmp.getRight());
}
}
return false;
}
public static void main(String[] args) {
BinaryTreeNode rootNode = TreeUtil.createRandomBinaryTree();
BTreePrinter.printBinaryTreeNode(rootNode);
for(int i=0;i<20;i++){
System.out.println(i + " Value found: " + findInBT(rootNode,i));
}
}
}
========================================================================
Refer Core Classes: http://arunj2ee.blogspot.in/2017/05/tree-core-and-utility-classes.html========================================================================
0 comments:
Post a Comment