Invert Binary Tree. Θ(n)

2018-03-19  本文已影响4人  R0b1n_L33
from random import randrange

class BinaryTree(object):
    """Binary Tree"""
    def __init__(self, node:int=0, leftTree=None, rightTree=None):
        super(BinaryTree, self).__init__()
        self.node = node
        self.leftTree = leftTree
        self.rightTree = rightTree

    def __str__(self):
        s = 'Node is ' + str(self.node) + ', leftTree is '
        if self.leftTree:
            s += str(self.leftTree.node)
        else:
            s += str(None)
        s += ', rightTree is '
        if self.rightTree:
            s += str(self.rightTree.node)
        else:
            s += str(None)
        s += '\n'
        return s
        
def invertBinaryTree(root:BinaryTree) -> BinaryTree:
    if not root:
        return None
    queue = [root]
    while queue:
        tree = queue.pop(0)
        tree.leftTree, tree.rightTree = tree.rightTree, tree.leftTree
        if tree.leftTree:
            queue.append(tree.leftTree)
        if tree.rightTree:
            queue.append(tree.rightTree)
    return root

def buildBinaryTreeWithDepth(depth:int, scope:int) -> BinaryTree:
    root = BinaryTree(node=randrange(scope))
    if depth <= 0:
        return root
    queue = [root]
    for i in range(depth):
        shallow = queue[:]
        for tree in shallow:
            queue.remove(tree)
            tree.leftTree = BinaryTree(node=randrange(scope))
            tree.rightTree = BinaryTree(node=randrange(scope))
            queue.append(tree.leftTree)
            queue.append(tree.rightTree)
    return root

上一篇下一篇

猜你喜欢

热点阅读