美文网首页
Invert Binary Tree. Θ(n)

Invert Binary Tree. Θ(n)

作者: R0b1n_L33 | 来源:发表于2018-03-19 22:35 被阅读4次
    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
    
    

    相关文章

      网友评论

          本文标题:Invert Binary Tree. Θ(n)

          本文链接:https://www.haomeiwen.com/subject/kwymqftx.html