二叉树的一些操作的代码实现

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

较为直观的打印二叉树

def printTree(root):
    if not root:
        return
    print("Binary Tree: ")
    printInOrder(root, 0, 'H', 10)

def printInOrder(root, height, preStr, length):
    if not root:
        return
    printInOrder(root.right, height+1, 'v', length)
    string = preStr + root.val + preStr
    leftLen = (length - len(string)) // 2
    rightLen = length - len(string)- leftLen
    res = " "*leftLen + string + " "*rightLen
    print(" "*height*length + res)
    printInOrder(root.left, height+1, '^', length)

计算树的深度

def getDepth(root):
    if not root:
        return 0
    return 1 + max(getDepth(root.left), getDepth(root.right))

计算树的带权路径长度

def getWPL(root, depth=0):
    if not root:
        return 0
    if not root.left and not root.right:
        return depth * int(root.val)
    return getWPL(root.left, depth + 1) + getWPL(root.right, depth + 1)

打印二叉树的边界节点

给定一棵二叉树的头节点,按照如下两种标准分别实现二叉树边界节点的逆时针打印。
标准一:

  1. 头节点为边界节点
  2. 叶节点为边界节点
  3. 如果节点在其所在层中的最左边或最右边,那么也是边界节点

标准二:

  1. 头节点为边界节点
  2. 叶节点为边界节点
  3. 树左边界延伸下去的路径为边界节点
  4. 树右边界延伸下去的路径为边界节点
#标准一
def printEdge1(root):
    def getHeight(root, height=0):
        if not root:
            return 0
        return max(getHeight(root.left, height+1), getHeight(root.right, height+1)) + 1

    def getMap(root, i, map):
        if not root:
            return
        if map[i][0] == None:
            map[i][0] = root
        map[i][1] = root
        getMap(root.left, i+1, map)
        getMap(root.right, i+1, map)

    def printLeafNotInMap(root, i, map):
        if not root:
            return
        if not root.left and not root.right and root != map[i][0] and \
                root != map[i][1]:
            print(root.val, end=' ')
        printLeafNotInMap(root.left, i+1, map)
        printLeafNotInMap(root.right, i+1, map)

    if not root:
        return
    height = getHeight(root)
    map = [[None for i in range(2)] for j in range(height)]
    getMap(root, 0, map)
    for i in range(len(map)):
        print(map[i][0].val, end=' ')
    printLeafNotInMap(root, 0, map)
    for i in range(len(map)-1, -1, -1):
        if map[i][0] != map[i][1]:
            print(map[i][1].val, end=' ')
#标准二
def printEdge2(root):
    def printLeft(root, isPrint):
        if not root:
            return
        if isPrint or (root.left == None and root.right == None):
            print(root.val, end=' ')
        printLeft(root.left, isPrint)
        printLeft(root.right, bool(isPrint and root.left == None))

    def printRight(root, isPrint):
        if not root:
            return
        printRight(root.left, bool(isPrint and root.right == None))
        printRight(root.right, isPrint)
        if isPrint or (root.left == None and root.right == None):
            print(root.val, end=' ')


    if not root:
        return
    print(root.val, end=' ')
    if root.left and root.right:
        printLeft(root.left, True)
        printRight(root.right, True)
    elif root.left:
        printEdge2(root.left)
    elif root.right:
        printEdge2(root.right)

二叉树的序列化和反序列化

说明:二叉树被记录成文件的过程叫作二叉树的序列化,通过文件内容重建原来二叉树的过程叫作二叉树的反序列化

#二叉树的序列化和反序列化(先序)
def serialByPre(root):
    if not root:
        return '#!'
    res = root.val + '!'
    res += serialByPre(root.left)
    res += serialByPre(root.right)
    return res

def reconByPreString(preStr):
    def reconPreOrder(values):
        key = values.pop(0)
        if key == '#':
            return None
        root = TreeNode(key)
        root.left = reconPreOrder(values)
        root.right = reconPreOrder(values)
        return root

    values = preStr.split('!')
    return reconPreOrder(values)
#二叉树的序列化和反序列化(层次)
def serialByLevel(root):
    if root == '#':
        return '#!'
    stack = []
    stack.append(root)
    res = root.val + '!'
    while stack:
        root = stack.pop()
        if root.left:
            res += root.left.val + '!'
            stack.append(root.left)
        else:
            res += '#!'
        if root.right:
            res += root.right.val + '!'
            stack.append(root.right)
        else:
            res += '#!'
    return res

def reconByLevelString(levStr):
    def generateNode(key):
        if key == '#':
            return None
        return TreeNode(key)

    values = levStr.split('!')
    head = generateNode(values.pop(0))
    queue = []
    if head:
        queue.append(head)
    while queue:
        root = queue.pop(0)
        root.left = generateNode(values.pop(0))
        root.right = generateNode(values.pop(0))
        if root.left:
            queue.append(root.left)
        if root.right:
            queue.append(root.right)
    return head
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值