二叉树的遍历与快速排序

#树的遍历,递归
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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值