Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Search Root Element in Binary Search Tree. #23

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Heet-Patel-5304
Copy link
Contributor

Description

The provided code defines a method for searching a value in a binary search tree (BST). It utilizes a recursive approach to traverse the tree. The TreeNode class represents a node in the tree, containing an integer value and references to left and right child nodes. The searchBST method takes the root of the tree and the value to be searched as inputs and returns the node containing the value if found; otherwise, it returns null.

Explanation

1. Class Definition:

  • The TreeNode class defines the structure of a node in the binary search tree. It has three constructors: a default constructor, one that initializes the node with a value, and another that initializes the node with a value and its left and right children.

2. Search Method (searchBST):

1. Parameters:

  • TreeNode root: The root node of the BST.
  • int val: The value to search for.

2. Base Case:

  • If the root is null, it means the value is not found, and it returns null.

3. Value Check:

  • If the value of the current node (root.val) matches val, the method returns the current node.

4. Recursive Search:

  • If root.val is greater than val, the method recursively searches the left subtree.
  • If root.val is less than val, it recursively searches the right subtree.

@Heet-Patel-5304 Heet-Patel-5304 changed the title Search Element in Binary Search Tree. Search Root Element in Binary Search Tree. Oct 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant