欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二叉树前序、中序、后序遍历,递归和非递归实现

程序员文章站 2022-05-16 14:54:04
...
class TreeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

class Order:
    def __init__(self):
        self.result = []

    def preOrder(self, node):
        if not node:
            return
        self.result.append(node.data)
        self.preOrder(node.left)
        self.preOrder(node.right)

    def preOrder2(self, node):
        nodeList = []
        while nodeList or node:
            if node:
                self.result.append(node.data)
                nodeList.append(node)
                node = node.left
            else:
                node = nodeList.pop()
                node = node.right

    def midOrder(self, node):
        if not node:
            return
        self.midOrder(node.left)
        self.result.append(node.data)
        self.midOrder(node.right)

    def midOrder2(self, node):
        nodeList = []
        while nodeList or node:
            if node:
                nodeList.append(node)
                node = node.left
            else:
                node = nodeList.pop()
                self.result.append(node.data)
                node = node.right

    def posOrder(self, node):
        if not node:
            return
        self.posOrder(node.left)
        self.posOrder(node.right)
        self.result.append(node.data)

    def posOrder2(self, node):
        nodeList = []
        while nodeList or node:
            if node:
                nodeList.append(node)
                node = node.left
            else:
                node = nodeList[-1]
                if not node.right:
                    self.result.append(node.data)
                    nodePop = nodeList.pop()
                    nodeNow = nodeList[-1]
                    # 出栈的是左子树节点,跳到右子树
                    if nodeNow.left == nodePop:
                        node = nodeNow.right
                    # 出栈的是右子树节点时,双亲节点出栈
                    elif nodeNow.right == nodePop:
                        self.result.append(nodeNow.data)
                        nodeList.pop()
                        if nodeList:
                            node = nodeList[-1].right
                        else:
                            node = None
                else:
                    node = node.right
                    nodeList.append(node)

if __name__ == '__main__':
    A = TreeNode(1)
    B = TreeNode(2)
    C = TreeNode(3)
    D = TreeNode(4)
    E = TreeNode(5)
    F = TreeNode(6)
    A.left = B
    A.right = C
    B.left = D
    B.right = E
    C.left = F
    ss = Order()
    ss.posOrder(A)
    print(ss.result)