LeetCode //C - 700. Search in a Binary Search Tree

发布时间:2024年01月23日

700. Search in a Binary Search Tree

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node’s value equals val and return the subtree rooted with that node. If such a node does not exist, return null.
?

Example 1:

在这里插入图片描述

Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]

Example 2:

在这里插入图片描述

Input: root = [4,2,7,1,3], val = 5
Output: []

Constraints:
  • The number of nodes in the tree is in the range [1, 5000].
  • 1 < = N o d e . v a l < = 1 0 7 1 <= Node.val <= 10^7 1<=Node.val<=107
  • root is a binary search tree.
  • 1 < = v a l < = 1 0 7 1 <= val <= 10^7 1<=val<=107

From: LeetCode
Link: 700. Search in a Binary Search Tree


Solution:

Ideas:

This function recursively searches the BST: if the val is less than the current node’s value, it searches the left subtree; if val is greater, it searches the right subtree. When the value is found, it returns the current node, which is the root of the subtree containing all nodes with values that make the subtree a valid BST. If the search ends at a NULL node (i.e., the value is not found), it returns NULL.

Code:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

struct TreeNode* searchBST(struct TreeNode* root, int val) {
    // Base case: root is null or root's value is the one we're searching for
    if (root == NULL || root->val == val) {
        return root;
    }
    
    // Since it's a BST, if the value is less than the root's value,
    // we will search in the left subtree
    if (val < root->val) {
        return searchBST(root->left, val);
    }
    
    // If the value is greater than the root's value,
    // we will search in the right subtree
    return searchBST(root->right, val);
}
文章来源:https://blog.csdn.net/navicheung/article/details/135739149
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。