简体   繁体   English

如何从左到右反转二叉树?

[英]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? 如何为BinaryTree类编写反向(self)方法,该方法使用引用来引用子树?

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何确定二叉树节点是左还是右子节点? - How to determine if a Binary Tree node is a Left or Right child? 如何反转python中的for循环并从左到右打印元素 - how to reverse the for loop in python and print the elements from left to right 在二叉树插入中,只有左树是右树。 正确的树是错误的 - In binary tree insertion, only the left tree is right. The right tree is wrong 在Python中按级别顺序打印二叉树而没有左或右 - Printing Binary Tree in Level Order without Left or Right in Python 二叉树添加左和添加右节点不添加 - binary tree add left and add right nodes not adding 为什么 Python 中的列表元素是从左到右索引的? 我怎样才能扭转这种局面? - Why are list elements in Python indexed from left to right? How can I reverse this? 如果节点中没有左子节点,如何在二叉搜索树中获取兄弟节点 - how to get sibling node in binary search tree if there is no left child in a node 如何在二叉树中找出左孩子的数量? (Python) - How to figure out a number of left children in binary tree? (Python) 在 Python 中删除二叉树节点。 为什么 self != parent.left 或 parent.right? - Deleting a binary tree node in Python. Why self != parent.left or parent.right? 在递归查找最大路径总和时,附加二叉树的左或右方向 - While recursively finding max path sum, append left or right direction of binary tree
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM