Give an algorithm for searching an element in binary tree

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;

/*
 * Que: Give an algorithm for searching an element in binary tree
 * Using recursion
 * Time Complexity: O(n), Space Complexity: O(n)
 */
public class Que3 {
public static boolean findInBT(BinaryTreeNode root, int data) {
if (root == null)
return false;

if (root.getData() == data)
return true;

return findInBT(root.getLeft(), data)
|| findInBT(root.getRight(), data);
}

public static void main(String[] args) {
BinaryTreeNode rootNode = TreeUtil.makeSampleBinaryTree();
BTreePrinter.printBinaryTreeNode(rootNode);
System.out.println("5 Value found:" + findInBT(rootNode,5));
System.out.println("9 Value found:" + findInBT(rootNode,9));
}
}
========================================================================
Refer Core Classes: http://arunj2ee.blogspot.in/2017/05/tree-core-and-utility-classes.html
========================================================================
Share on Google Plus

About Admin

Arun is a JAVA/J2EE developer and passionate about coding and managing technical team.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment