Java program to search a node in a Binary Tree
Trees are the non-linear data structure that stores data hierarchically. The tree is a collection of elements called nodes. Nodes are connected through edges and contain data. The first node of the tree is called Root. Each node may or may not have children node. The node which doesn’t have any child node is called leaf.
The binary tree is another kind of tree data structure in which each node can have at most two children. That is, each node in the binary tree will have data, left child and right child.
Above diagram represents a binary tree in which 1 represent the root node of the tree. Node 2 has 4 as its left child and Node 3 has 5 as its left child and 6 as its right child. Nodes 4, 5 and 6 are leaf nodes as they don?t have any child node.
Explanation:
In this program, we will search a particular value in the binary tree. If it is present, print the message “Element is present in the binary tree” else print the message “Element is not present in the binary tree”. In a nutshell, we will first compare data of root with data of node to be searched. If the match is found, set the flag to true. Else, search the node in left subtree and then in the right subtree.
Algorithm
- Define Node class which has three attributes namely: data left and right. Here, left represents the left child of the node and right represents the right child of the node.
- When a node is created, data will pass to data attribute of the node and both left and right will be set to null.
- Define another class which has two attribute root and flag.
- Root represents the root node of the tree and initializes it to null.
- The Flag will be used to check whether the given node is present in the tree or not. Initially, it will be set to false.
a. searchNode() will search for a particular node in the binary tree:
- It checks whether the root is null, which means the tree is empty.
- If the tree is not empty, it will compare temp?s data with value. If they are equal, it will set the flag to true and return.
- Traverse left subtree by calling searchNode() recursively and check whether the value is present in left subtree.
- Traverse right subtree by calling searchNode() recursively and check whether the value is present in the right subtree.
Program:
Output:
Element is present in the binary tree.