二叉树-----遍历
Posted lee-yl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树-----遍历相关的知识,希望对你有一定的参考价值。
一、前序遍历:
递归方式:
def preorder(tree): if tree: print(tree.val) preorder(tree.getLeftChild()) preorder(tree.getRightChild())
非递归方式:时间复杂度O(n),空间复杂度O(n)
def preOrder(head): if not head: return None res ,stack = [] , [head] while stack: cur = stack.pop() res.append(cur.val) if cur.right: stack.append(cur.right) if cur.left: stack.append(cur.left) return res
二、中序遍历:
递归方式:
def inorder(tree): if tree: inorder(tree.left) print(tree.val) inorder(tree.right)
非递归方式:
def InOrder(head): if not head: return None res ,stack = [] , [] cur = head while stack or cur: if cur: stack.append(cur) cur = cur.left else: cur = stack.pop() res.append(cur.val) cur =cur.right return res
三、后序遍历:
递归
def postorder(tree): if tree: postorder(tree.left) postorder(tree.right)) print(tree.val)
非递归:
def PosOrder(head): if not head: return [] s1 , s2 = [head] , [] cur = head while s1: cur = s1.pop() s2.append(cur.val) if cur.left: s1.append(cur.left) if cur.right: s1.append(cur.right) return s2[::-1]
以上是关于二叉树-----遍历的主要内容,如果未能解决你的问题,请参考以下文章