Search Root Element in Binary Search Tree. #23
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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. ThesearchBST
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 returnsnull
.Explanation
1. Class Definition:
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:
null
, it means the value is not found, and it returnsnull
.3. Value Check:
root.val
) matchesval
, the method returns the current node.4. Recursive Search:
root.val
is greater thanval
, the method recursively searches the left subtree.root.val
is less thanval
, it recursively searches the right subtree.