Python之二叉树Binarytree

二叉树是树的简化版,除根节点之外的所有节点都有一个父节点,任意节点都可以最多有一个左子节点和右子节点。

二叉树的遍历是非常重要的算法,主要分为深度优先遍历和广度优先遍历。

其中深度优先遍历按照访问根节点和左右子节点的访问顺序,分为先根遍历(preorder),中根遍历(inorder)和后根遍历(postorder)。

顾名思义,先根遍历的访问原则是先访问根节点,然后左子节点,右子节点;

 

中根遍历的访问原则是先左子节点,然后根节点,最后右子节点;

后根遍历的访问原则是先左子节点,然后右子节点,最后根节点。

广度优先遍历(breadthfirst),就是像下面这样,访问完一层再访问下一层,如下:

闲言少叙,上代码:

import Queue

class Node:
    def __init__(self,value=None,left=None,right=None):
        self.value=value
        self.left=left
        self.right=right
        
def preorder_trav(root):
    if root==None:
        return 
    print root.value
    preorder_trav(root.left)
    preorder_trav(root.right)
    
def inorder_trav(root):
    if root ==None:
        return
    inorder_trav(root.left)
    print root.value
    inorder_trav(root.right)
    
def postorder_trav(root):
    if root ==None:
        return 
    postorder_trav(root.left)
    postorder_trav(root.right)
    print root.value

def breadthfirst_trav(root):
    # Create a queue and add the root node to it.
    q=Queue.Queue()
    q.put(root)
    # Visit each node in the tree.
    while not q.empty() :
        # Remove the next node from the queue and visit it.
        node = q.get()
        print( node.value )
        # Add the two children to the queue.
        if node.left is not None :
            q.put( node.left )
        if node.right is not None :
            q.put( node.right )
    
    
if __name__=='__main__':
    root=Node('A',Node('B',Node('D'),Node('E')),Node('C',Node('F'),Node('G'))) 
    print 'preorder_trav:'
    preorder_trav(root)
    print 'inorder_trav:'
    inorder_trav(root)
    print 'postorder_trav:'
    postorder_trav(root)
    print 'breadthfirst_trav:'
    breadthfirst_trav(root)

 二叉树的递归遍历代码看起来很简单,有点像伪代码,但功能很强大,非递归方法实现的就有点复杂了,等我研究明白再分享出来。

posted @ 2017-03-09 11:10  Mars.wang  阅读(1087)  评论(0编辑  收藏  举报