How to search a node in binary tree using java

In this program, we will learn how to search a node in a binary tree in Java. First, we will learn what is a binary tree. A binary is a different type of data structure. In the binary tree, each node can contain a maximum of two child nodes & a minimum one. In the binary tree, each node consists of data.

Java program to search a node in a binary tree

public class BinaryTree {

  Node root;

  public void addNode(int key, String name) {
    Node newNode = new Node(key, name);

    if (root == null) {
      root = newNode;
    } else {
      Node focusNode = root;
      Node parent;
      while (true) {
        parent = focusNode;
        if (key < focusNode.key) {

          focusNode = focusNode.leftChild;
          if (focusNode == null) {
            parent.leftChild = newNode;
            return;
          }

        } else {
          focusNode = focusNode.rightChild;
          if (focusNode == null) {

            parent.rightChild = newNode;
            return; 

          }

        }

      }
    }
  }
  public Node findNode(int key) {
    Node focusNode = root;
    while (focusNode.key != key) {
      if (key < focusNode.key) {
        focusNode = focusNode.leftChild;
      } else {
        focusNode = focusNode.rightChild;
      }
      if (focusNode == null)
        return null;
    }
    return focusNode;
  }
public static void main(String[] args) {
    BinaryTree theTree = new BinaryTree();
    theTree.addNode(50, "mayank");
    theTree.addNode(25, "sahill");
    theTree.addNode(15, "khushal");
    theTree.addNode(30, "yash");
    theTree.addNode(75, "ankur");
    theTree.addNode(85, "nilender");
    System.out.println("\nNode with the key 85");
    System.out.println(theTree.findNode(85));

}
}
class Node {

  int key;
  String name;

  Node leftChild;
  Node rightChild;

  Node(int key, String name) {

    this.key = key;
    this.name = name;

  }

  public String toString() {
    return name + " key " + key;

  }

}

in this program, we have searched node 85 and print the details that are written on a node 85.

Now, we will learn the algorithm of the program & step of algorithm are-:

  1. first, we check the root node if a root node was null then return null.
  2. If a root node was greater than a search node then goes to the right child node of the tree.
  3. If a root node was less than a search node then goes to the left child node of the tree.

In this program, we have already declared the nodes and the number of nodes is node1, node2, node3, node4, node5.
The number of searching node 5.

The output of the program



OUTPUT-: Node with the key 85
         Nilender has the key 85

You may also learn,

Leave a Reply

Your email address will not be published. Required fields are marked *