【Python】二叉树遍历

【Python】二叉树遍历

广度遍历(层次遍历)

非递归:用队列实现

def traverse(self, tree):
    if not tree:
        return []
    res = []
    q = Queue.Queue()
    q.put(tree)
    while not q.empty():
        level = []
        length = q.qsize()
        for i in range(length):
            p = q.get()
            level.append(p.val)
            if p.left:
                q.put(p.left)
            if p.right:
                q.put(p.right)
        res.append(level)
    return res

深度遍历

  • 前序遍历

前序遍历(根结点–>左结点–>右结点)

递归

def PreOrder(self, tree, res):
    if not tree:
        return []
    res.append(tree.val)
    self.PreOrder(tree.left, res)
    self.PreOrder(tree.right, res)
    return res

非递归:用栈实现

def preorder(self, bintree):
    if not bintree:
        return []
    res = []
    tree = []
    p = bintree
    while p or tree:
        while p:
            tree.append(p)
            res.append(p.val)
            p = p.left
        if tree:
            p = tree.pop()
            p = p.right
    return res
  • 中序遍历

中序遍历(左结点–>根结点–>右结点)

递归

def InOrder(self, tree, res):
    if not tree:
        return []
    self.InOrder(tree.left, res)
    res.append(tree.val)
    self.InOrder(tree.right, res)
    return res

非递归:用栈实现

def inorder(self, bintree):
    if not bintree:
        return []
    res = []
    tree = []
    p = bintree
    while p or tree:
        while p:
            tree.append(p)
            p = p.left
        if tree:
            p = tree.pop()
            res.append(p.val)
            p = p.right
    return res
  • 后序遍历

后序遍历(左结点–>右结点–>根结点)

递归

def PostOrder(self, tree, res):
    if not tree:
        return []
     self.PostOrder(tree.left, res)
    self.PostOrder(tree.right, res)
    res.append(tree.val)
    return res

非递归:用栈实现

def postorder(self, bintree):
    if not bintree:
        return []
    tree = []
    res = []
    tree.append(bintree)
    while tree:
        p = tree.pop()
        res.insert(0, p.val)
        if p.left:
            tree.append(p.left)
        if p.right:
            tree.append(p.right)
        return res

你可能感兴趣的:(Python,二叉树,Python)