Python 二叉搜索树的两个独立getHeight算法的运行时

Python 二叉搜索树的两个独立getHeight算法的运行时,python,algorithm,performance,recursion,binary-search-tree,Python,Algorithm,Performance,Recursion,Binary Search Tree,对于二进制搜索树(不一定是平衡的BST),我有两个单独的getHeight()方法实现,一个是迭代的,另一个是递归的。这里是迭代的一个: def height(root): #iterative approach, uses a stack for a depth first search max_height = 0 myStack = [root] currentNode = None root.level = True while len(mySt

对于二进制搜索树(不一定是平衡的BST),我有两个单独的getHeight()方法实现,一个是迭代的,另一个是递归的。这里是迭代的一个:

def height(root): #iterative approach, uses a stack for a depth first search
    max_height = 0
    myStack = [root]
    currentNode = None
    root.level = True

    while len(myStack) != 0:
        currentNode = myStack[-1]
        if currentNode.left is not None and currentNode.left.level is not True:
            myStack.append(currentNode.left)
            currentNode.left.level = True
            continue
        if currentNode.right is not None and currentNode.right.level is not True:
            myStack.append(currentNode.right)
            currentNode.right.level = True
            continue
        elif (currentNode.left is None or currentNode.left.level is True) and (currentNode.right is None or currentNode.right.level is True):
            height = len(myStack) - 1
            if height > max_height:
              max_height = height
            myStack.pop()
return max_height
下面是递归方法:

def recurseHeight(root):
    add = 0
    l, r = 0, 0
    if root.left is not None:
        l = 1 + recurseHeight(root.left)
    if root.right is not None:
        r = 1 + recurseHeight(root.right)

    return l if l > r else r
所以,我知道从空间复杂度的角度来看,递归算法更好。然而,根据我的理解,迭代算法的运行时间是O(n)(因为它必须搜索所有n个节点,并且在该点之前不会停止),但我想知道递归算法的运行时间是什么。我知道我必须使用主定理,我的一部分认为它也是O(n),因为无论发生什么,我都必须访问所有节点,但我不确定。有人能帮忙找到递归算法的运行时吗


(旁注,我这样做是为了练习面试——如果有人有很好的问题/学习资源,请毫不犹豫地大声自豪地说:)

正如你所说的那样,这是O(n),因为你总是访问树中的每个节点,并且只访问每个节点一次,这意味着你需要O(n)对于递归版本的工作

,您不需要猜测,只需分析这两种方法并准确了解它们的内存和CPU使用情况。看见另外,欢迎来到这个网站:你可能想阅读,和。