Specify the root node and a value of the Binary Search Tree (BST. You need to find the node whose value is equal to the given value in BST. Returns the subtree with the node as the root. If the node does not exist, null is returned.
For example,
Given Binary Search Tree: 4/2 7/1 3 and value: 2
You should return the following subtree:
2 / \ 1 3
In the preceding example5
But because no node value is5
, We should returnNULL
.
Analysis: the binary search tree has the property that the Left subtree value is smaller than the root node, and the right subtree value is greater than the root node, therefore, if the value to be searched is smaller than the root node, you can continue searching in the left subtree. If the value is greater than the root node, you can continue searching in the right subtree.
Code:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */10 class Solution {11 public:12 TreeNode* searchBST(TreeNode* root, int val) {13 if(root == NULL){14 return NULL;15 }16 else if(root->val == val){17 return root;18 }19 else if(val > root->val){20 return(searchBST(root->right, val));21 }22 else if(val < root->val){23 return(searchBST(root->left, val));24 }25 else{26 return NULL;27 }28 }29 };
F
Search in LeetCode-700-Binary Search Tree