简体   繁体   中英

How to reverse a binary tree from left to right?

How to write a reverse(self) method for the BinaryTree class which uses references to refer to subtrees?

def __init__(self, value, l = None, r = None) :
    self.data = value
    self.left = l
    self.right = r

def insert_left(self, value) :
    self.left = BinaryTree(value, l = self.left)

def insert_right(self, value) :
    self.right = BinaryTree(value, l = self.right)

def set_value(self, value) :
    self.data = value

def get_value(self) :
    return self.data

def get_left_subtree(self) :
    return self.left

def get_right_subtree(self) :
    return self.right

def create_string(self, indent) :
    info = str(self.data) + '---+'
    if self.left :
        info += '\n(l)' + indent + self.left.create_string(indent + '  ')
    if self.right :
        info += '\n(r)' + indent + self.right.create_string(indent + '  ')
    return info

def __str__(self) :
    representation = self.create_string("  ")
    return representation
def reverse(self) :
# reverse(self)
# ===============
# always returns a copy of the tree with the following changes:
# if self has no subtrees then no side-effects
# if self has only one subtree
# then reverses that subtree
# and moves it to the other side
# else reverses both subtrees
# and swaps the two reversed subtrees
#
def reverse(self):
    self.left, self.right = self.right, self.left
    if self.left != None:
        self.left.reverse()
    if self.right != None:
        self.right.reverse()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM