二叉搜索樹中查找元素
時(shí)間復(fù)雜度為:O(H),H為樹的高度靶病,平均時(shí)間復(fù)雜度O(logN)轧房,最壞時(shí)間復(fù)雜度O(N)
空間復(fù)雜度:遞歸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
};