Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.
For example,
Given the tree: 4 / \ 2 7 / \ 1 3 And the value to search: 2
You should return this subtree:
2 / \ 1 3
In the example above, if we want to search the value 5
, since there is no node with value 5
, we should return NULL
.
Note that an empty tree is represented by NULL
, therefore you would see the expected output (serialized tree format) as []
, not null
.
這道題讓我們搜索一個二叉搜索樹,既然是二叉搜索樹,而不是普通的二叉樹,那么我們肯定要利用二叉搜索樹特定的性質來解題,即左<根<右。那么就是說任意一個結點的左子樹中的所有結點均小於當前結點,其右子樹中的所有結點均大於當前結點。那么這不就是一個天然的二分么,當仁不讓的二分搜索法呼之欲出啊。首先判空,如果當前結點不存在,直接返回空。如果當前結點值等於目標值,返回當前結點。接下來就看如果當前結點值大於目標值,則對左子結點調用遞歸函數,否則就對右子結點調用遞歸函數,參見代碼如下:
解法一:
class Solution { public: TreeNode* searchBST(TreeNode* root, int val) { if (!root) return NULL; if (root->val == val) return root; return (root->val > val) ? searchBST(root->left, val) : searchBST(root->right, val); } };
我們也可以使用迭代形式來解,使用一個while循環,思路都是一樣的,如果當前結點存在,且結點值不等於目標值,那么若結點值大於目標值,則當前結點指向其左子結點,否則指向其右子結點,參見代碼如下:
解法二:
class Solution { public: TreeNode* searchBST(TreeNode* root, int val) { while (root && root->val != val) { root = (root->val > val) ? root->left : root->right; } return root; } };
類似題目:
Closest Binary Search Tree Value
Insert into a Binary Search Tree
參考資料:
https://leetcode.com/problems/search-in-a-binary-search-tree/