Discuss / Python / 递归函数理论上都能改写成循环

递归函数理论上都能改写成循环

霸道名

#1 Created at ... [Delete] [Delete and Lock User]

请教求理论引用地址。 二叉树的遍历如何用循环来写呢?

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

看这个:

http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2.1

One reason that the distinction between process and procedure may be confusing is that most implementations of common languages (including Ada, Pascal, and C) are designed in such a way that the interpretation of any recursive procedure consumes an amount of memory that grows with the number of procedure calls, even when the process described is, in principle, iterative. As a consequence, these languages can describe iterative processes only by resorting to special-purpose 'looping constructs' such as do, repeat, until, for, and while. The implementation of Scheme we shall consider in chapter 5 does not share this defect. It will execute an iterative process in constant space, even if the iterative process is described by a recursive procedure. An implementation with this property is called tail-recursive. With a tail-recursive implementation, iteration can be expressed using the ordinary procedure call mechanism, so that special iteration constructs are useful only as syntactic sugar.

chaif87

#3 Created at ... [Delete] [Delete and Lock User]

很好写啊,利用栈实现深度优先遍历,队列实现广度优先遍历。

## 二叉树遍历

##        0
##     ___|___
##    |       |  
##    1       4  
##   _|_     _|_    
##  |   |   |   |
##  2   3   5   6


class BinaryTree:
    def __init__(self, data, lchild=None, rchild=None):
        self.data = data
        self.rchild = rchild
        self.lchild = lchild


node2 = BinaryTree(2)
node3 = BinaryTree(3)
node5 = BinaryTree(5)
node6 = BinaryTree(6)


node1 = BinaryTree(1, lchild=node2, rchild=node3)
node4 = BinaryTree(4, lchild=node5, rchild=node6)

node0 = BinaryTree(0, lchild=node1, rchild=node4)


## 深度优先遍历二叉树
def depth_first_search(root):
    stack = []
    stack.append(root)
    while len(stack) != 0 :
        node = stack[-1]
        print(node.data, end=' ')
        stack.pop()
        if node.rchild != None:
            stack.append(node.rchild)
        if node.lchild != None:
            stack.append(node.lchild)
    print('\n')


depth_first_search(node0)
## 0 1 2 3 4 5 6


## 广度优先遍历二叉树
def breadth_first_search(root):
    quene = []
    quene.append(root)
    while len(quene) != 0 :
        node = quene[0]
        print(node.data, end=' ')
        quene.pop(0)
        if node.lchild != None:
            quene.append(node.lchild)
        if node.rchild != None:
            quene.append(node.rchild)
    print('\n')

breadth_first_search(node0)
## 0 1 4 2 3 5 6

  • 1

Reply