# 700. Search in a Binary Search Tree

## 1.問題

* 給予一個BST, 找出sub tree

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LK9tyj-9xqz7rz8YtMH%2F-LK9xxN72i47Y_olbPXZ%2F2018081802.jpg?alt=media\&token=19aceeec-7077-43e9-be95-66db85f528ab)

## 2.想法

* Inorder traversal

## 3.程式碼

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val) {
        if (root == NULL) {
            return NULL;
        }
        
        TreeNode* left = searchBST(root->left, val);
        if (left != NULL && left->val == val) {
            return left;
        }
        if (root->val == val) {
            return root;
        }
        TreeNode* right = searchBST(root->right, val);
        if (right != NULL && right->val == val) {
            return right;
        }
        return NULL;
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LK9tyj-9xqz7rz8YtMH%2F-LK9yGV-HN-tIN4jzbge%2F2018081803.jpg?alt=media\&token=63fb088d-00b1-4afb-96b8-e5357b966d3e)
