美文网首页
700. Search in a Binary Search T

700. Search in a Binary Search T

作者: jluemmmm | 来源:发表于2021-01-27 12:54 被阅读0次

    二叉搜索树中查找元素

    时间复杂度为: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
    };
    

    相关文章

      网友评论

          本文标题:700. Search in a Binary Search T

          本文链接:https://www.haomeiwen.com/subject/efxazktx.html