[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 value
  • right sub-tree的所有Node value 都大於root value
  • Binary Search Tree的key/value都是unique的

現在我們知道什麼是BST了。這個問題是要在BST中找val,我們通過以下幾個條件以及遞歸幫我們求解:

  • left sub-tree的所有Node value 都小於root value
  • right 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;
        }
    }
};