Given a Binary Search Tree (BST) and a target value, your task is to determine whether this value exists in the BST. If it does, return the node that contains this value; otherwise, return null
or indicate that the value is not found.
Find a Value in a BST - Algorithm, Visualization, Examples
Visualization Player
Problem Statement
Examples
Solution
Algorithm Steps
Code
C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}
TreeNode* findInBST(TreeNode* root, int target) {
if (root == NULL) return NULL;
if (root->val == target) return root;
return target < root->val ? findInBST(root->left, target) : findInBST(root->right, target);
}
int main() {
TreeNode* root = createNode(10);
root->left = createNode(5);
root->right = createNode(15);
int target = 5;
TreeNode* result = findInBST(root, target);
if (result) {
printf("Found node with value: %d\n", result->val);
} else {
printf("Value not found\n");
}
return 0;
}
Comments
Loading comments...