二叉树广度遍历

#encoding=utf-8
from Queue import Queue
class TreeNode(object):
    def __init__(self,var,left=None,right=None):
        self.var=var
        self.left=left
        self.right=right
 
class PreOder(object):
    retlist=[]
    def __init__(self,root=None):
        self.root=root
 
    def preOder(self):
        queue=Queue()
        queue.put(self.root)#生成队列
        if self.root==None:
            return None
        while queue.empty() is not True:#队列内容是否为空
            node=queue.get()
            PreOder.retlist.append(node.var)#相对根节点
            if node.left!=None:
                queue.put(node.left)
            if node.right!=None:
                queue.put(node.right)
        return PreOder.retlist
 
if __name__=="__main__":
    tree=TreeNode(1)
    tree.left=TreeNode(2,left=TreeNode(4),right=TreeNode(5))
    tree.right=TreeNode(3,left=TreeNode(6))
    content=PreOder(tree)
    print content.preOder()
posted @ 2019-07-14 21:31  张特别  阅读(287)  评论(0编辑  收藏  举报