public class BinarySearchNodes {// Binary tree node static class Node { int data; Node left, right; Node(int data) { thi

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

public class BinarySearchNodes {// Binary tree node static class Node { int data; Node left, right; Node(int data) { thi

Post by answerhappygod »

public class BinarySearchNodes {// Binary tree node
static class Node
{
int data;
Node left, right;
Node(int data)
{
this.data = data;
left = right = null;
}
};
// Function to traverse the tree in preorder
// and check if the given node exists in it
static boolean ifNodeExists( Node node, int key)
{
if (node == null)
return false;
if (node.data == key)
return true;
// then recur on left subtree /
boolean res1 = ifNodeExists(node.left, key);
// node found, no need to look further
if(res1) return true;
// node is not found in left,
// so recur on right subtree /
boolean res2 = ifNodeExists(node.right, key);
return res2;
}
// Driver Code
public static void main(String args[])
{
Node root = new Node(0);
root.left = new Node(1);
root.left.left = new Node(3);
root.left.left.left = new Node(7);
root.left.right = new Node(4);
root.left.right.left = new Node(8);
root.left.right.right = new Node(9);
root.right = new Node(2);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.right.right = new Node(10);
int key = 10;
if (ifNodeExists(root, key))
System.out.println("YES");
else
System.out.println("NO");
}
}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply