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.html
For example, node
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
.post
Note that an empty tree is represented by NULL
, therefore you would see the expected output (serialized tree format) as []
, not null
.this
這道題讓咱們搜索一個二叉搜索樹,既然是二叉搜索樹,而不是普通的二叉樹,那麼咱們確定要利用二叉搜索樹特定的性質來解題,即左<根<右。那麼就是說任意一個結點的左子樹中的全部結點均小於當前結點,其右子樹中的全部結點均大於當前結點。那麼這不就是一個自然的二分麼,當仁不讓的二分搜索法呼之欲出啊。首先判空,若是當前結點不存在,直接返回空。若是當前結點值等於目標值,返回當前結點。接下來就看若是當前結點值大於目標值,則對左子結點調用遞歸函數,不然就對右子結點調用遞歸函數,參見代碼以下:url
解法一:spa
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循環,思路都是同樣的,若是當前結點存在,且結點值不等於目標值,那麼若結點值大於目標值,則當前結點指向其左子結點,不然指向其右子結點,參見代碼以下:code
解法二:orm
class Solution { public: TreeNode* searchBST(TreeNode* root, int val) { while (root && root->val != val) { root = (root->val > val) ? root->left : root->right; } return root; } };
相似題目:htm
Closest Binary Search Tree Value
Insert into a Binary Search Tree
參考資料:
https://leetcode.com/problems/search-in-a-binary-search-tree/