Search In A Binary Search Tree
Complete Data: 2020-12-08
Description
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.
For example,
Example
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.
Solution
/*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }*//*** @param {TreeNode} root* @param {number} val* @return {TreeNode}*/var searchBST = function (root, val) {if (!root || !val) return null;return root.val === val? root: root.val > val? searchBST(root.left, val): searchBST(root.right, val);};
Complexity Analysis
- In worst case,

The binary search tree is a skewed binary search tree. Height of the binary search tree becomes n. So, Time complexity of BST Operations = O(n). In this case, binary search tree is as good as unordered list with no benefits.
- In best case,
The binary search tree is a balanced binary search tree. Height of the binary search tree becomes log(n). So, Time complexity of BST Operations = O(logn).
