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 1:
    700. Search in a Binary Search Tree - 图1
    Input: root = [4,2,7,1,3], val = 2 Output: [2,1,3]
    Example 2:
    700. Search in a Binary Search Tree - 图2
    Input: root = [4,2,7,1,3], val = 5 Output: []

    Constraints:

    • The number of nodes in the tree is in the range [1, 5000].
    • 1 <= Node.val <= 107
    • root is a binary search tree.
    • 1 <= val <= 107

    Runtime: 92 ms, faster than 84.88% of JavaScript online submissions for Search in a Binary Search Tree.
    Memory Usage: 45.2 MB, less than 33.90% of JavaScript online submissions for Search in a Binary Search Tree.

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @param {number} val
    12. * @return {TreeNode}
    13. */
    14. var searchBST = function(root, val) {
    15. if (!root) {
    16. return null;
    17. }
    18. if (root.val === val) {
    19. return root;
    20. }
    21. if (root.val > val) {
    22. return searchBST(root.left, val);
    23. }
    24. return searchBST(root.right, val);
    25. };

    Runtime: 88 ms, faster than 92.84% of JavaScript online submissions for Search in a Binary Search Tree.
    Memory Usage: 45.6 MB, less than 8.59% of JavaScript online submissions for Search in a Binary Search Tree.

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @param {number} val
    12. * @return {TreeNode}
    13. */
    14. var searchBST = function(root, val) {
    15. if (!root) {
    16. return null;
    17. }
    18. let node = root;
    19. while(node) {
    20. if (node.val === val) {
    21. return node;
    22. }
    23. if (node.val > val) {
    24. node = node.left;
    25. } else {
    26. node = node.right;
    27. }
    28. }
    29. return null;
    30. };