二叉树-深度优先遍历(栈遍历方式)

深度优先遍历分为先序遍历,中序遍历,以及后序遍历;而深度遍历的方式又分为递归深度遍历和栈深度遍历。我们现在讨论栈深度遍历的实现方式:

#!/usr/bin/env python
#coding:utf-8

class TreeNode(object):
    def __init__(self):
        self.data = '#'
        self.lchild = None
        self.rchild = None

class Tree(TreeNode):
    def __init__(self):
        self.root = TreeNode()
        self.myQueue = []

    #Create a tree
    def create_tree(self,tree):
        data = raw_input('->')
        if data == '#':
            tree = None
        else:
            tree.data = data
            tree.lchild = TreeNode()
            self.create_tree(tree.lchild)
            tree.rchild = TreeNode()
            self.create_tree(tree.rchild)

    def visit(self,tree):
        #输入#代表空树
        if tree.data is not '#':
            print str(tree.data)+'\t'

    def pre_stack(self,tree):
        if tree == None:
            return
        myStack = []
        none = tree
        while node or myStack:
            while node:
                print node.data
                myStack.append(node)
                node = node.lchild
            node = myStack.pop()
            node = node.rchild

    def in_stack(self,tree):
        if tree == None:
            return
        myStack = []
        node = tree
        while node or myStack:
            myStack.append(node)
            node=node.lchild
        node=myStack.pop()
        print node.data
        node=node.rchild

    def post_stack(self,tree):
        if tree == None:
            return
        myStack1 = []
        myStack2 = []
        node=tree
        myStack1.append(node)
        while myStack1:
            node = myStack1.pop()
            if node.lchild:
                myStack1.append(node.lchild)
            if node.rchild:
                myStack1.append(node.rchild)
            myStack2.append(node)
        while myStack2:
            print myStack2.pop().data
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值