二叉树问题---二叉树的前中后序的递归,非递归及Morris遍历

class TreeNode:
    def __init__(self, x):
        root.val = x
        root.left = None
        root.right = None

创建二叉树

def create_tree(root):
    element = input("Enter a key: ")
    if element == '#':
        root = None
    else:
        root = TreeNode(element)
        root.left = create_tree(root.left)
        root.right = create_tree(root.right)
    return root

前序遍历

def pre_order(root):
    if root:
        print(root.val,end=' ')
        pre_order(root.left)
        pre_order(root.right)

中序遍历

def mid_order(root):
    if root:
        mid_order(root.left)
        print(root.val, end=' ')
        mid_order(root.right)

后序遍历

def post_order(root):
    if root:
        post_order(root.left)
        post_order(root.right)
        print(root.val, end=' ')

非递归前序遍历

def preorder(root):
    if not root:
        return
    stack = []
    while root or len(stack):
        if root:
            stack.append(root)
            print(root.val, end=' ')
            root = root.left
        else:
            root = stack.pop()
            root = root.right

非递归中序遍历

def midorder(root):
    if not root:
        return
    stack = []
    while root or stack:
        if root:
            stack.append(root)
            root = root.left
        else:
            root = stack.pop()
            print(root.val, end=' ')
            root = root.right

非递归后序遍历

def postorder(root):
    if not root:
        return
    stack1 = []
    stack2 = []
    while root or stack1:
        if root:
            stack1.append(root)
            stack2.append(root.val)
            root = root.right
        else:
            root = stack1.pop()
            root = root.left
    while stack2:
        print(stack2.pop(), end=' ')

非递归后序遍历(使用一个栈)

说明:使用一个变量c来记录每次弹出的元素,保证元素不会重复进栈

def postOrder(root):
    if not root:
        return
    stack = []
    stack.append(root)
    c = None
    while stack:
        c = stack[-1]
        if c.left and c.left != root and c.right != root:
            stack.append(c.left)
        elif c.right and c.right != root:
            stack.append(c.right)
        else:
            print(stack.pop().val, end=' ')
            root = c

Morris前序遍历

def morrisPre(root):
    if not root:
        return
    while root:
        cur = root.left
        if cur:
            while cur.right and cur.right != root:
                cur = cur.right
            if not cur.right:
                cur.right = root
                print(root.val, end=' ')
                root = root.left
                continue
            else:
                cur.right = None
        else:
            print(root.val, end=' ')
        root = root.right

Morris中序遍历

def morrisIn(root):
    if not root:
        return
    while root:
        cur = root.left
        if cur:
            while cur.right and cur.right != root:
                cur = cur.right
            if not cur.right:
                cur.right = root
                root = root.left
                continue
            else:
                cur.right = None
        print(root.val, end=' ')
        root = root.right

Morris后序遍历

def morrisPost(root):
    def printRightEdge(root):
        tail = reverseEdge(root)
        cur = tail
        while cur:
            print(cur.val, end=' ')
            cur = cur.right
        reverseEdge(tail)

    def reverseEdge(root):
        pre = None
        while root:
            next = root.right
            root.right = pre
            pre = root
            root = next
        return pre

    if not root:
        return
    head = root
    while root:
        cur = root.left
        if cur:
            while cur.right and cur.right != root:
                cur = cur.right
            if not cur.right:
                cur.right = root
                root = root.left
                continue
            else:
                cur.right = None
                printRightEdge(root.left)
        root = root.right
    printRightEdge(head)

层次遍历

def levelorder(root):
    if not root:
        return
    queue = []
    queue.append(root)
    while queue:
        root = queue.pop(0)
        print(root.val, end=' ')
        if root.left:
            queue.append(root.left)
        if root.right:
            queue.append(root.right)
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉树非递归遍历常用的方法有两种,一种是使用栈,一种是使用 Morris 遍历。下面我将分别给出两种方法的 Python 代码实现。 ## 栈实现非递归遍历 ```python class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def preorderTraversal(root): if not root: return [] stack, res = [root], [] while stack: node = stack.pop() res.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return res def inorderTraversal(root): if not root: return [] stack, res = [], [] while stack or root: if root: stack.append(root) root = root.left else: node = stack.pop() res.append(node.val) root = node.right return res def postorderTraversal(root): if not root: return [] stack, res = [root], [] while stack: node = stack.pop() res.append(node.val) if node.left: stack.append(node.left) if node.right: stack.append(node.right) return res[::-1] ``` 上述代码实现了二叉树遍历遍历后序遍历,分别用 `preorderTraversal`、`inorderTraversal` 和 `postorderTraversal` 表示。这些函数的实现都是基于栈的非递归遍历方法,使用栈保存待访问的节点。在遍历时先将根节点入栈,然后循环执行以下操作: - 弹出栈顶节点,记录其值; - 将栈顶节点的右子节点(如果有)入栈; - 将栈顶节点的左子节点(如果有)入栈。 由于栈的特性,上述循环会先访问左子树,然后是右子树,符合二叉树遍历的先左后右的规则。针对后序遍历,需要将结果数组反转。 ## Morris 遍历实现非递归遍历 ```python class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def inorderTraversal(root): if not root: return [] cur, res = root, [] while cur: if not cur.left: res.append(cur.val) cur = cur.right else: pre = cur.left while pre.right and pre.right is not cur: pre = pre.right if not pre.right: pre.right = cur cur = cur.left else: pre.right = None res.append(cur.val) cur = cur.right return res ``` 上述代码实现了二叉树遍历,使用 Morris 遍历方法。Morris 遍历方法基于线索二叉树的思想,利用空闲的指针保存访问过的节点,从而避免使用栈或者递归占用额外的空间。具体实现方法如下: - 如果当节点的左子节点为空,记录当节点的值,然后将当节点指向其右子节点; - 如果当节点的左子节点不为空,找到其左子树的最右节点,记为 `pre`; - 如果 `pre` 的右指针为空,将其右指针指向当节点,然后将当节点指向其左子节点; - 如果 `pre` 的右指针不为空,说明当节点的左子树已经访问完毕,记录当节点的值,然后将 `pre` 的右指针置为空,将当节点指向其右子节点。 由于 Morris 遍历方法只使用了常数级别的空间,因此在空间复杂度上优于基于栈的遍历方法。但是,由于需要修改树的结构,因此在时间复杂度上可能会劣于基于栈的遍历方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值