#树的遍历,递归
class Node(object):
def __init__(self, val ,left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorder(root):#前序遍历 根、左、右
if not root:
return None
print(root.val)
preorder(root.left)
preorder(root.right)
def postorder(root):#后序遍历 左、右、根
if not root:
return None
postorder(root.left)
postorder(root.right)
print(root.val)
def inorder(tree):#中序遍历 左、根、右
if not root:
return None
inorder(root.left)
print(root.val)
inorder(root.right)
#树的遍历,非递归
def preTraverse(root): #前序非递归遍历
if not root:
return None
stack = [root]
res = []
while stack:
tmp = stack.pop()
res.append(tmp.val)
if tmp.right:
stack.append(tmp.right)
if tmp.left:
stack.append(tmp.left)
return res
def postTraverse(root):#后序非递归遍历
if not root:
return None
stack =[root]
res = []
while stack:
tmp = stack.pop()
res.append(tmp.val)
if tmp.left:
stack.append(tmp.left)
if tmp.right:
stack.append(tmp.right)
return res.reverse()
def midTraverse(root):#中序非递归遍历
if not root:
return None
stack = []
res = []
while stack or root:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
res.append(root.val)
root = root.right
return res
def layer_traverse(root):#层次遍历
if not root:
return None
queue = [root]
res = []
while queue:
tmp = queue.pop(0)
res.append(tmp.val)
if tmp.left:
queue.append(tmp.left)
if tmp.right:
queue.append(tmp.right)
return res
def layer_traverse2(root):#层序遍历,每层结果单独保存于一个list
if not root:
return None
queue = [root]
res = []
while queue:
layer_res = []
for i in range(len(queue)):
tmp = queue.pop(0)
layer_res.append(tmp.val)
if tmp.left:
queue.append(tmp.left)
if tmp.right:
queue.append(tmp.right)
res.append(layer_res)
return res
def quick_sort(array):#快速排序
if len(array) < 2:
return array
else:
pivot = array[0]
less = [i for i in array[1:] if i <= pivot]
greater = [i for i in array[1:] if i > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)
二叉树的遍历与快速排序
最新推荐文章于 2022-05-31 17:01:23 发布