【问题标题】:Is loop and recursion interchangeable?循环和递归可以互换吗?
【发布时间】:2019-11-12 16:48:09
【问题描述】:

很多人说循环和递归基本上是一样的。两者之间的唯一区别是某些算法在递归或迭代中更容易理解。此外,由于函数调用的开销,总是首选循环。但是,这里有一个 python 代码来获取二叉搜索树的高度。如何使用循环编写它?

bst = [(1, 2), (3, None), (None, None), (None, None)]

def recursion_height(tree, v=0):
    if v is None:
        return -1
    else:
        return max(recursion_height(tree, tree[v][0]), recursion_height(tree, tree[v][1])) + 1

【问题讨论】:

    标签: python recursion iteration binary-search-tree


    【解决方案1】:

    这可以使用队列迭代地实现。

    # A binary tree node 
    class Node:
    # Constructor to create new node 
    def __init__(self, data): 
        self.data = data  
        self.left = None
        self.right = None
    
    
    # Iterative method to find height of Binary Tree 
    def treeHeight(root): 
    
        # Base Case 
        if root is None: 
            return 0
    
        # Create a empty queue for level order traversal 
        q = [] 
    
        # Enqueue Root and Initialize Height  
        q.append(root) 
        height = 0 
    
        while(True):   
            # nodeCount(queue size) indicates number of nodes 
            # at current level 
            nodeCount = len(q) 
            if nodeCount == 0 : 
                return height  
    
            height += 1 
    
            # Dequeue all nodes of current level and Enqueue 
            # all nodes of next level 
            while(nodeCount > 0): 
                node = q[0] 
                q.pop(0) 
                if node.left is not None: 
                    q.append(node.left) 
                if node.right is not None: 
                    q.append(node.right) 
    
                nodeCount -= 1
    
    # Driver program to test above function 
    # Let us create binary tree shown in above diagram 
    root = Node(1) 
    root.left = Node(2) 
    root.right = Node(3) 
    root.left.left = Node(4) 
    root.left.right = Node(5) 
    
    print "Height of tree is", treeHeight(root)
    

    【讨论】:

    • 感谢您的回复。我不确定我能理解你的功能。你的函数的输入是什么?二叉搜索树在哪里?你能提供一个示例输入和输出吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    相关资源
    最近更新 更多