一、首先二叉树的定义:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
构建一棵二叉树:
class Node(object):
def __init__(self, val):
self.val = val
self.lchild = None
self.rchild = None
class Tree(object):
def __init__(self):
self.root = None
self.myQueue = []
def add(self, val):
node = Node(val)
if self.root == None:
self.root = node
self.myQueue.append(self.root)
else:
while True:
point = self.myQueue[0]
if point.lchild == None:
point.lchild = node
self.myQueue.append(point.lchild)
return
elif point.rchild == None:
point.rchild = node
self.myQueue.append(point.rchild)
self.myQueue.pop(0)
return
二、前序遍历
递归实现
def preorder(root,res=[]):
if not root:
return
res.append(root.val)
preorder(root.lchild,res)
preorder(root.rchild,res)
return res
迭代实现
def preorder(root):
res = []
if not root:
return []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
if node.rchild:
stack.append(node.rchild)
if node.lchild:
stack.append(node,lchild)
return res
三、中序遍历
递归实现
def inorder(root,res=[]):
if not root:
return
inorder(root.lchild,res)
res.append(root.val)
inorder(root.rchild,res)
return res
迭代实现
def inorder(root):
stack = []
node = root
res = []
while stack or node:
while node:
stack.append(node)
node = node.lchild
node = stack.pop()
res.append(node.val)
node = node.rchild
return res
四、后序遍历
递归实现
def laorder(root,res=[]):
if not root:
return
laorder(root.lchild,res)
laorder(root.rchild,res)
res.append(root.val)
return res
迭代实现
def laorder(root):
stack = [root]
res = []
while stack:
node = stack.pop()
if node.lchild:
stack.append(node.left)
if node.rchild:
stack.append(node.right)
res.append(node.val)
return res[::-1]
五、层次遍历
迭代
def levelorder(root):
queue = [root]
res = []
while queue:
node = queue.pop(0)
if node.lchild:
queue.append(node.lchild)
if node.rchild:
queue.append(node.rchild)
res.append(node.val)
return res
运行结果:
参考博客:https://www.jb51.net/article/157422.htm、https://blog.csdn.net/Bone_ACE/article/details/46718683、https://blog.csdn.net/wzngzaixiaomantou/article/details/81294915