[Leetcode] Search in a Binary Search Tree(Easy)
LeetCode 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
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
Input: root = [4,2,7,1,3], val = 5
Output: []
How can we solve this problem?
在解決問題之前,我們需要知道什麼是Binary Search Tree
。根據BST
的定義:
Binary Search Tree
基於Binary Tree
left sub-tree
的所有Node value 都小於root valueright sub-tree
的所有Node value 都大於root valueBinary Search Tree
的key/value都是unique的
現在我們知道什麼是BST
了。這個問題是要在BST
中找val
,我們通過以下幾個條件以及遞歸幫我們求解:
left sub-tree
的所有Node value 都小於root valueright sub-tree
的所有Node value 都大於root value
如果val
是小於root,就移動到左子樹(left sub-tree)
,否者移動到右子樹(right sub-tree)
,直到找到val
並返回root的pointer
或者沒有找到返回null
Solution:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root == nullptr) return root;
//check val
if(root->val > val){
//go to left
return searchBST(root->left,val); //
}else if(root->val < val){
return searchBST(root->right,val);
}else{
return root;
}
}
};