700. Search in a Binary Search T
2021-01-27 本文已影响0人
jluemmmm
二叉搜索树中查找元素
时间复杂度为:O(H),H为树的高度,平均时间复杂度O(logN),最坏时间复杂度O(N)
空间复杂度:递归O(H),迭代O(1)
- Runtime: 96 ms, faster than 76.47%
- Memory Usage: 45 MB, less than 73.82%
- 递归
/**
* 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 === null) return null
if (root.val === val) return root
if (root.val < val) return searchBST(root.right, val)
if (root.val > val) return searchBST(root.left, val)
return null
};
- 迭代
/**
* 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) {
while(root !== null && root.val !== val) {
root = root.val > val ? root.left : root.right;
}
return root
};