简体   繁体   English

使用大师定理,这个 function 的运行时间是多少

[英]what would be the run time of this function using master's theorem

    IN-TREE(p, k) 
    if p == NIL 
        return FALSE 
    else if p.key == KEY 
        return TRUE 
    else 
        return IN-TREE(p.left, k) or IN-TREE(p.right, k)

p points to a node in a complete linked binary tree and has each node p has a key called p.key, a pointer to its left subtree p.left, and a pointer to its right subtree p.right. p 指向完全链接二叉树中的一个节点,并且每个节点 p 都有一个名为 p.key 的键,一个指向其左子树 p.left 的指针,以及一个指向其右子树 p.right 的指针。 An empty subtree is written as NIL.一个空的子树写成 NIL。

What would be the run time of this function using master's theorem?使用大师定理,这个 function 的运行时间是多少?

It is clearly evident that in the worst-case scenario, you are going to look over all the nodes in the tree to match the node's key with KEY.很明显,在最坏的情况下,您将查看树中的所有节点以将节点的键与 KEY 匹配。

Therefore time complexity of this solution is O(n), where n is the number of nodes in the Tree.因此,此解决方案的时间复杂度为 O(n),其中 n 是树中的节点数。

A complete tree of depth d has 2^d-1 nodes.一棵深度为d的完整树有2^d-1个节点。 So in the worst case (when the key is not found),所以在最坏的情况下(找不到密钥时),

T(d) = C + T(d-1) + T(d-1).

If we rewrite in terms of the number of nodes,如果我们根据节点数重写,

T(N) = C + 2 T((N-1)/2).

As the independent term is constant, the solution is linear in N.由于独立项是常数,解在 N 中是线性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM